SQL Aliases
Aliases give a column or table a temporary, friendlier name for the duration of the query.
Column aliases
SQL
SELECT name AS customer,
email AS contact,
price * quantity AS line_total
FROM line_items;
The AS keyword is optional but makes intent clearer. In SQL Server you can also write customer = name.
Table aliases
SQL
SELECT c.name, o.total FROM customers AS c JOIN orders AS o ON o.customer_id = c.id;
Table aliases are mandatory once a column name exists in more than one joined table.
Aliases with spaces or keywords
SQL
SELECT total AS "Total Revenue" FROM orders;
Use double quotes (ANSI), backticks (MySQL), or square brackets (SQL Server) to wrap aliases that contain spaces, punctuation, or reserved words.
Where aliases work — and don't
| Clause | Can use SELECT alias? |
|---|---|
WHERE | No — evaluated before SELECT |
GROUP BY | Postgres/MySQL yes; SQL Server no |
HAVING | Usually yes |
ORDER BY | Yes — runs after SELECT |
Tip: Short, one-letter table aliases (
c, o) keep multi-join queries readable. Long aliases hurt as much as no aliases at all.Example
Example
SELECT c.name AS customer,
o.total AS amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id;
Try it Yourself »
Exercise
Give the customers table a one-letter alias.
FROM customers
c
Two letters; aliasing keyword (optional but explicit).
Discussion
Loading…