iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL Aliases

Aliases give a column or table a temporary, friendlier name for the duration of the query.

Column aliases

SQL
SELECT name      AS customer,
       email     AS contact,
       price * quantity AS line_total
FROM line_items;

The AS keyword is optional but makes intent clearer. In SQL Server you can also write customer = name.

Table aliases

SQL
SELECT c.name, o.total
FROM customers AS c
JOIN orders    AS o ON o.customer_id = c.id;

Table aliases are mandatory once a column name exists in more than one joined table.

Aliases with spaces or keywords

SQL
SELECT total AS "Total Revenue"
FROM orders;

Use double quotes (ANSI), backticks (MySQL), or square brackets (SQL Server) to wrap aliases that contain spaces, punctuation, or reserved words.

Where aliases work — and don't

ClauseCan use SELECT alias?
WHERENo — evaluated before SELECT
GROUP BYPostgres/MySQL yes; SQL Server no
HAVINGUsually yes
ORDER BYYes — runs after SELECT
Tip: Short, one-letter table aliases (c, o) keep multi-join queries readable. Long aliases hurt as much as no aliases at all.

Example

Example
SELECT c.name AS customer,
       o.total AS amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id;
Try it Yourself »

Exercise

Give the customers table a one-letter alias.

FROM customers c

Test yourself

Q1. AS keyword is…
Q2. Aliases with spaces are wrapped in…
Q3. You CAN use a SELECT alias in…

Discussion

Loading…