SQL Aliases

Aliases give tables or columns a temporary name that exists only for the duration of a single query.

What an alias is

An alias is a temporary label you attach to a column or a table inside a query. It does not change anything stored in the database; it simply renames something for the length of that one statement. Aliases make results easier to read, let you shorten long table names, and are essential when a query refers to the same table more than once.

You create an alias with the AS keyword, though AS is optional in most databases and is often left out. Whether or not you write AS, the effect is the same: the new name replaces the original in the query's output or in the rest of the statement.

Column aliases

A column alias renames a column in the result set. This is most helpful when a column has a cryptic name or when you compute a value and want a clear heading for it.

Rename columns in the output

SELECT customer_name AS name,
       city AS location
FROM Customers;
Note: If an alias contains spaces or special characters, wrap it in double quotes, for example AS "Full Name". Some databases, such as MySQL, also accept back-ticks for this purpose.

Name a calculated column

SELECT product_name,
       price * quantity AS total_value
FROM OrderItems;

Table aliases

A table alias gives a table a short nickname you can use throughout the query. This keeps queries concise, especially when they involve joins, and it lets you qualify column names without repeating a long table name.

Shorten table names in a join

SELECT c.customer_name, o.order_date, o.order_total
FROM Customers AS c
JOIN Orders AS o
  ON c.customer_id = o.customer_id;

Table aliases are not just convenient here, they are required in a self join, where the same table appears twice and each copy needs its own name so the database can tell them apart.

Alias typeApplies toExampleEffect
Column aliasA selected column or expressionprice AS costRenames the column in the output
Column aliasA calculated valueprice * qty AS totalGives the computed column a heading
Table aliasA table in FROM or JOINCustomers AS cProvides a short name for the table
Table aliasThe same table used twiceEmployees AS e1, Employees AS e2Distinguishes the two copies in a self join
  • Aliases are temporary and last only for the current query.
  • The AS keyword is optional for both column and table aliases.
  • Column aliases make output headings clear, particularly for calculated values.
  • Table aliases shorten queries and are required in self joins.
  • Quote an alias that contains spaces or reserved words.
Note: A column alias defined in the SELECT list usually cannot be used in the WHERE clause, because WHERE is evaluated before the SELECT list is applied. Many databases do allow the alias in ORDER BY and GROUP BY, but to filter on a computed value in WHERE you must repeat the full expression.

Exercise: SQL Aliases

What is the main purpose of a SQL alias?