Lesson 8. Aliases

Aliases are a way of renaming things. This comes in handy in a variety of ways. There are two kinds of aliases.

Column Aliases

Column aliases let you rename a column by using the SQL keyword AS. There are a few reasons you would want to rename a column.

  1. When you create a column based on a calculation, SQL Server does not automatically give it a name. You have to do that.

  2. When you are creating views for users you do not want to use ugly database names. You can rename the column to something that will show up pretty in the user’s BI tool.

  3. Sometimes you want to rename things for your own personal sanity. When you are pulling data from more than one table and those tables have the same column names, it can become confusing in a hurry.

In the case of scenario two, you may want to create a column name with a space in it. To do that, you have to wrap your alias in brackets.

Table Aliases

Table aliases let you rename tables. There are a lot of reasons to do this. Those reasons will become apparent when you start pulling data from more than one table. A table alias makes it easier to refer to a table and helps you keep columns straight.

To alias a table, just put what you want to call the table behind the table name in the FROM clause.

Examples

Column Alias Example

USE AdventureWorks2016

SELECT
Name AS [Product Name],
ProductNumber AS [Product Number]
FROM Production.Product

Table Alias Example

USE AdventureWorks2016

SELECT
p.ProductID,
p.Name,
p.ProductNumber
FROM Production.Product p

Last updated