Table aliases in SQL
This topic contains and tries to cover following subjects:
- Explanation of Table aliases in SQL
- Syntax of using a Table alias in a SQL query
- An example of Table alias in SQL
Articles provides answer to following questions and issues:
- Why Table aliases are used in a SQL query?
- How Table aliases are used in a SQL query?
Explanation of Table aliases in SQL
Table aliases are used to name a Table with a shorter name in essence, some sort of acronym of table. When a SQL query is created to retrieve data from a data source as result data set, programmer may want to use a shorter name to refer that table within in query. After a Table alias is assigned to a Table in query following the FROM statement; that table can be referred with its alias.
SELECT HRDEP.Name,
HRDEP.GroupName
FROM HumanResources.Department AS HRDep;
Syntax of Table Aliases in SQL
To alias a Table, after FROM statement which indicates data source, SQL keyword "AS" is added to tell query the upcoming Text is the short name of Table. Example:
SELECT -column name- FROM -Table Name- AS -short table name-
Example of Table aliases in SQL
To demonstrate a Table aliases with example, Adventureworks of Microsoft SQL server is queried.
In normal case, programmer types every time table long time before the column name:
SELECT HumanResources.Department.Name,
HumanResources.Department.GroupName
FROM HumanResources.Department;
Using table Alias:
USE AdventureWorks;
GO
SELECT HRDEPT.Name,
HRDEPT.GroupName
FROM HumanResources.Department AS HRDEPT;
In above query, we access to the "HumanResources.Department" table with FROM statement. It is our data source in that query. We get the columns of "Name" and "GroupName". Table aliases allow programmer to name the table with shorter name. We can use a Table alias as follows:
Output is: