</>
Skip to content
SQL lessons (23/54)

SQL — Aliases

What is an Alias?

An alias gives a column or table a temporary different name using the AS keyword. It makes queries easier to read and is required when you need to reference a calculated column by name.

Column Aliases

SELECT
  first_name AS "First Name",
  last_name AS "Last Name",
  salary AS "Annual Salary"
FROM employees;

The output headers now say "First Name", "Last Name", and "Annual Salary" instead of the raw column names.

Aliases with Calculations

This is where aliases really shine — you can't reference a calculation without one:

SELECT
  product_name,
  price,
  quantity,
  price * quantity AS total_value
FROM inventory;

Without AS total_value, you'd have no way to refer to price * quantity in a WHERE or ORDER BY clause.

Table Aliases

When joining tables, aliases save typing and prevent ambiguity:

SELECT
  e.first_name,
  e.last_name,
  d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id = d.id;

You can omit the AS keyword — employees e works the same as employees AS e. Most developers skip it for tables but keep it for columns.

Using Aliases in ORDER BY

SELECT
  first_name,
  salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;

Aliases in Subqueries

SELECT avg_salary.department, avg_salary.avg_sal
FROM (
  SELECT department_id, AVG(salary) AS avg_sal
  FROM employees
  GROUP BY department_id
) AS avg_salary
WHERE avg_salary.avg_sal > 75000;

Rules for Aliases

  • Wrap the alias in double quotes if it contains spaces or special characters
  • Aliases only exist for the duration of the query
  • You cannot use a column alias in a WHERE clause (use it in HAVING or ORDER BY instead)

Common Mistakes

-- Wrong: can't use alias in WHERE
SELECT salary AS annual_salary
FROM employees
WHERE annual_salary > 50000;

-- Right: repeat the expression or use HAVING
SELECT salary AS annual_salary
FROM employees
WHERE salary > 50000;

Practice

  1. Write a query that aliases first_name and last_name as "Full Name" by concatenating them
  2. Calculate monthly salary (salary / 12) and give it a readable alias
  3. Use table aliases in a three-way JOIN

Related Topics

Frequently Asked Questions about Aliases

What is Aliases in SQL?

Aliases is a fundamental concept in SQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Aliases?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Aliases.

Why is Aliases important in SQL?

Aliases is essential for SQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.