Advertisement
❮ Previous: SQL Between Next: SQL Null Values ❯

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:

SELECT first_name AS "First Name", email_address AS email
FROM customers;
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

-- Both do the exact same thing:
SELECT first_name AS name FROM employees;
SELECT first_name name FROM employees;
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;
❮ Previous: SQL Between Next: SQL Null Values ❯
Advertisement