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

  1. Column alias: SELECT first_name AS fname FROM employees;
  2. Table alias: SELECT e.first_name FROM employees AS e;
  3. Expression alias: SELECT price * quantity AS total FROM order_items;
  4. Use aliases in ORDER BY: SELECT first_name AS name FROM employees ORDER BY name;
  5. 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 SELECT cannot be used in the same WHERE clause because of logical processing order.
  • Spaces in aliases require quoting: AS "First Name".r