What is a column alias?
A column alias is a name given to a column that changes how it appears in the results. For example, to return the Name column from the Production.Product table but have the column’s name appear as “Product Name” in the results:
SELECT Name AS [Product Name]
If you look in the results section, you will see “Product Name” listed as the column name instead of just “Name”. There are a few reasons to use a column alias (we will talk about some of them in more advanced lessons), but one reason is to just make the columns easier to read. Many times, we will write a query and then bring the results into an Excel file to give to someone. Since most columns in a table do not have spaces or they use underscores in their place, column aliases give us a chance to clean them.
To return the top 100 SalesOrderNumbers from the Sales.SalesOrderHeader table but give it the column alias “Order Number”, we type:
SELECT TOP 100 SalesOrderNumber AS [Order Number]
You can create a column alias without spaces if you choose. However, if spaces exist in the alias, you must enclose the alias in either double quotes (“) or square brackets.
Complete the practice problems below to get more experience using column aliases.
- Return the top 100 rows from the Production.Product table. Select only the Name column and assign it the column alias “Standard Product Name”.
- Using the Person.Person table, return the FirstName and LastName columns. Assign the alias “First Name” and “Last Name” to the columns respectively.
Follow the link to review the basic SQL SELECT statement if you having trouble with some of the practice problems. As always, leave a comment if you have any questions!