SQLConfiguration SQLConfiguration

Select Data  «Prev  Next»
Lesson 5 Aliasing
Objective Use Aliases to make Queries easier to Write.

Use Aliases to make Queries easier to Write

An alias allows you to define an alternate name for the tables and columns in your queries. The two main advantages to using aliases are that they:
  1. Force columns returned in a query to use an alternate name
  2. Allow you to easily refer to a shorter table name within a query itself
To alias a column name, use the AS keyword in this syntax:


An alternative name for a database object that makes referring to that object easier. For example, if you construct a query by specifying the fully-qualified name of the database (including server name, database name, owner, and table), it is easier to alias this long string of objects so that you do not have to specify it every time you access it's objects. Note, however, that an alias is useful only within a single Transact-SQL statement.
[Table.]column AS alias

For example, to return the Zip column in the Employees table as an alias named ZipCode, you could use this statement:
FROM Employees

Issuing this Transact-SQL statement produces results similar to those shown in the illustration below:
SELECT Zip AS ZipCode FROM Employees

Notice that the column name which is returned in the query is the alias name, ZipCode, not the actual name of the column, Zip.
Aliasing table names within your queries can save you a lot of typing. This is because you can alias the table with a shorter name, allowing you to reference the shorter name. Aliasing a table name is also done with the AS keyword, just as when you alias a column name. To illustrate this point, consider this join that uses aliases:

SELECT e.LastName, t.Hours
FROM Timesheets AS t join 
  Employees AS e ON e.EmployeeID = t.EmployeeID

Notice that after each table name, there is an AS keyword followed by a single letter. This single letter (or any other name that you choose) is the alias name. This alias name can then be used in place of the table name in any syntax that requires a table name.
In the next lesson, you will learn how to join two select statements together with a union query.