Skip to main content

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.

Prior lesson

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_idorder_counttotal_spent
131407.98
321795.00
221348.00
4274.85
5189.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:

namepriceprice_with_tax
Laptop999.001098.90
Mouse29.9932.99
Desk349.00383.90
Chair199.00218.90
Notebook4.995.49

Common Mistake

Column aliases are not available in WHERE or HAVING

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:

namepricediscounted_price
Laptop999.00799.20
Mouse29.9923.99
Desk349.00279.20
Chair199.00159.20
Notebook4.993.99
Donate to this project