What are SQL aliases and how to use them
· Category: SQL & Databases
Short answer
Aliases are temporary names assigned to tables or columns using the AS keyword. They make queries shorter and results clearer.
Steps
- Column alias:
SELECT first_name AS fname FROM employees; - Table alias:
SELECT e.first_name FROM employees AS e; - Expression alias:
SELECT price * quantity AS total FROM order_items; - Use aliases in
ORDER BY:SELECT first_name AS name FROM employees ORDER BY name; - Reference aliased tables in joins:
SELECT o.id, c.name FROM orders AS o JOIN customers AS c ON o.customer_id = c.id;
Tips
- Aliases are especially useful in self-joins where the same table appears twice.
- Some databases allow omitting
AS, but including it improves readability.
Common issues
- Aliases defined in
SELECTcannot be used in the sameWHEREclause because of logical processing order. - Spaces in aliases require quoting:
AS "First Name".r