SQL Aliases
An alias is a short name that a query gives to a column or a table for that query only. The AS keyword sets the alias.
A column alias
The alias customer_name replaces name as the heading. The rows stay the same.
SELECT name AS customer_name FROM customers WHERE customer_id = 2;An expression with an alias
price * 2 works out a doubled price for each product. The alias names the new column double_price.
SELECT name, price * 2 AS double_price FROM products WHERE product_id = 4;Two aliased columns
Each column can carry its own alias. The headings of this answer use both aliases.
SELECT name AS product, price AS cost FROM products WHERE product_id = 7;A table alias
The letter c stands for the customers table in this query. The column names ride on the alias with a dot.
SELECT c.name, c.city FROM customers AS c WHERE c.customer_id = 5;Example
SELECT name AS item, price * 2 AS pair_price FROM products WHERE product_id = 7;Key points
- AS: the keyword that gives a column or a table an alias
- Alias: a short name that lives only inside one query
- A column alias becomes the heading of that column in the result.
- An expression column takes an alias so its heading stays short.
- A table alias shortens the table name inside the query.
In this example, the first alias renames the name column to item for this answer. The second column doubles the price, and its alias names it pair_price. The aliases change the headings of this answer and nothing in the table.
Note
Some engines allow an alias without AS, but this course always writes AS so the alias stands out.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DB Fiddle
Exercise
What does AS do in a query?