Aliases
SQL Aliases are a temporary name given to a table, view, or a column in a table for the specific query. Aliases make columns easier to identify and allow for shorthand text. Aliases are used to make complex SQL syntax easier to read where there are many joins and/or aggregations. The keyword “as” is used to denote an alias.
SQL Alias Column Syntax:
SELECT Column1 as NewName
FROM Table_Name
Alias Table Syntax:
SELECT
NewName .Column1,
NewName .Column2,
NewName .Column3
FROM Table_Name as NewName
Alias In Join Syntax:
SELECT
T1 .Column1,
T1.Column2,
T2.Column1,
T2.Column2
FROM Table1 as T1, Table2 as T2
WHERE T1.Column1=T2.Column1
Example:
Lets rename the column names of the following table
SalesReasonID |
Name |
ReasonType |
---|---|---|
1 |
Price |
Other |
2 |
On Promotion |
Promotion |
3 |
Magazine Advertisement |
Marketing |
4 |
Television Advertisement |
Marketing |
5 |
Manufacturer |
Other |
6 |
Review |
Other |
7 |
Demo Event |
Marketing |
8 |
Sponsorship |
Marketing |
9 |
Quality |
Other |
10 |
Other |
Other |
SELECT
SalesReasonID as ID,
Name as Sales_Reason_Name,
ReasonType as Sales_Reason_Type
FROM SalesReason
Results:
ID |
Sales_Reason_Name |
Sales_Reason_Type |
---|---|---|
1 |
Price |
Other |
2 |
On Promotion |
Promotion |
3 |
Magazine Advertisement |
Marketing |
4 |
Television Advertisement |
Marketing |
5 |
Manufacturer |
Other |
6 |
Review |
Other |
7 |
Demo Event |
Marketing |
8 |
Sponsorship |
Marketing |
9 |
Quality |
Other |
10 |
Other |
Other |
Table Alias Example:
SELECT
SR.SalesReasonID,
SR.Name,
SR.ReasonType
FROM SalesReason as SR
JOIN Alias Example:
SELECT
C.CustomerID,
C.StoreID,
S.ID,
S.Name
FROM Customer as C, Store as S
WHERE C.StoreID=S.ID
SQL Tutorial