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;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.
- 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.
Exercise: SQL Aliases
What is the main purpose of a SQL alias?