SQL aliases are used to give a table, or a column in a table, a temporary, more readable name.
An alias only exists for the duration of that query. Aliases are often used to make column names more readable.
SELECT column_name AS alias_name
FROM table_name;
SELECT column_name(s)
FROM table_name AS alias_name;
The AS keyword is optional. You can also write it like this:
SELECT column_name alias_name FROM table_name;
We will use the Customers and Orders tables for these examples.
Customers Table: CustomerID, CustomerName, ContactName, Country
Orders Table: OrderID, CustomerID, OrderDate
The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column.
SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;
The result set would look like this:
| ID | Customer |
|---|---|
| 1 | Alfreds Futterkiste |
| 2 | Ana Trujillo Emparedados |
Table aliases are most often used in JOIN operations to make the query shorter and more readable.
The following SQL statement selects all the orders from the customer with CustomerID=4. We use the Customers and Orders tables, and give them the table aliases "c" and "o" respectively.
SELECT o.OrderID, o.OrderDate, c.CustomerName FROM Customers AS c, Orders AS o WHERE c.CustomerName = 'Around the Horn' AND c.CustomerID = o.CustomerID;
Without aliases, the query would be longer and less readable:
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName = 'Around the Horn' AND Customers.CustomerID = Orders.CustomerID;