SQL Aliases
SQL aliases are temporary names given to columns or tables within a query. They are created using the AS keyword and only exist for the duration of that specific query execution.
Aliases do not alter the actual structures or names inside your physical database. They are purely used to make query outputs more readable or to shorten code.
Column Aliases
Column aliases are used to give the headings of your final query results descriptive, clean, or user-friendly names.
SELECT column_name AS alias_name
FROM table_name;
Real-World Examples:
- Renaming for clarity:
SELECT first_name AS "First Name", email_address AS email
FROM customers;
- Naming calculated columns (Essential): When you perform math or use functions, the database creates an ugly or blank column header. An alias fixes this.
SELECT product_name, price * 0.90 AS discounted_price
FROM inventory;
Table Aliases
Table aliases are used to temporarily rename a table. This is incredibly helpful when you are writing complex queries involving JOIN statements, as it saves you from typing out long, repetitive table names over and over.
SELECT t.column1, t.column2
FROM long_table_name AS t;
Real-World Example (Using Joins):
Instead of typing orders.order_date and customers.customer_name, you can abbreviate the tables to o and c:
SELECT o.order_id, o.order_date, c.customer_name
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.customer_id;
Syntax Rules and Practices
- The AS keyword is optional: In almost all modern databases (MySQL, PostgreSQL, SQL Server, Oracle), you can omit the word AS entirely and just use a space. However, explicitly writing AS makes your code much easier to read.
-- Both do the exact same thing:
SELECT first_name AS name FROM employees;
SELECT first_name name FROM employees;
- Handling Spaces: If you want your column alias to contain spaces or special characters, you must wrap it in double quotes ("") or square brackets ([] in SQL Server).
SELECT salary AS "Take Home Pay" FROM employees;
A Common Mistake: Using Aliases in WHERE
You cannot use a column alias inside a WHERE clause. This is because the database engine filters the rows (WHERE) before it selects and names the columns (SELECT).
-- ❌ THIS WILL FAIL:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;
-- THIS WORKS:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE (salary * 12) > 100000;