SQL Aliases

SQL Aliases

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.


Alias Syntax

Column Alias Syntax

SELECT column_name AS alias_name
FROM table_name;

Table Alias Syntax

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;

Demo Database

We will use the Customers and Orders tables for these examples.

Customers Table: CustomerID, CustomerName, ContactName, Country Orders Table: OrderID, CustomerID, OrderDate


Example 1: Column Aliases

The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column.

Column Alias Example

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

Example 2: Table Aliases

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.

Table Alias Example

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;