AS: Aliasing Columns and Tables
AS lets you assign a temporary name - an alias - to a column or table. Aliases make query output more readable and shorten long table names in joins.
The sample dataset is defined in the Introduction to SQL lesson.
Syntax
-- Column alias
SELECT column_name AS alias_name
FROM table_name;
-- Table alias
SELECT alias.column_name
FROM table_name AS alias;
AS is technically optional — the query below is equivalent and will run fine:
SELECT column_name alias_name
FROM table_name alias;
Always use AS anyway. It makes aliasing explicit and easy to spot when reading a query, especially once joins and subqueries are involved.
Examples
Example 1: Column aliases for readability
Without aliases, aggregate results get auto-generated column names that are often unhelpful.
-- Without aliases (ugly column names)
SELECT
customer_id,
COUNT(*),
SUM(total_amount)
FROM orders
GROUP BY customer_id;
-- With aliases (clean column names)
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC;
Result:
| customer_id | order_count | total_spent |
|---|---|---|
| 1 | 3 | 1407.98 |
| 3 | 2 | 1795.00 |
| 2 | 2 | 1348.00 |
| 4 | 2 | 74.85 |
| 5 | 1 | 89.97 |
Example 2: Table aliases
You can also alias a table, then use the alias to prefix column references. This becomes especially useful in joins (covered in a later lesson) where two tables may share a column name.
SELECT
o.order_id,
o.customer_id,
o.total_amount
FROM orders AS o;
Here o is just a shorter stand-in for orders. Every column reference is prefixed with o. to make it clear which table it comes from.
Example 3: Computed columns
You can alias the result of any expression.
SELECT
name,
price,
price * 1.1 AS price_with_tax
FROM products;
Result:
| name | price | price_with_tax |
|---|---|---|
| Laptop | 999.00 | 1098.90 |
| Mouse | 29.99 | 32.99 |
| Desk | 349.00 | 383.90 |
| Chair | 199.00 | 218.90 |
| Notebook | 4.99 | 5.49 |
Common Mistake
The WHERE and HAVING clauses are evaluated before SELECT, so they can't reference aliases defined in SELECT.
-- This fails:
SELECT total_amount * 0.9 AS discounted
FROM orders
WHERE discounted < 100; -- ERROR
-- Fix: repeat the expression
SELECT total_amount * 0.9 AS discounted
FROM orders
WHERE total_amount * 0.9 < 100;
Practice
Write a query that returns each product's name, price, and a computed column called discounted_price equal to price * 0.8 (20% off).
Show answer
SELECT
name,
price,
price * 0.8 AS discounted_price
FROM products;
Expected result:
| name | price | discounted_price |
|---|---|---|
| Laptop | 999.00 | 799.20 |
| Mouse | 29.99 | 23.99 |
| Desk | 349.00 | 279.20 |
| Chair | 199.00 | 159.20 |
| Notebook | 4.99 | 3.99 |