Column Aliases
The
AS keyword lets you rename a column in the output of a query, without changing anything about the underlying table. This is especially useful for computed columns, which otherwise show up with an unreadable, database-generated name.Renaming a column with AS
A simple alias
SQL
SELECT first_name AS "First Name",
last_name AS "Last Name"
FROM employees;Many databases also let you drop the word
AS entirely and just put the alias directly after the expression — both forms mean the same thing:AS is often optional
SQL
SELECT first_name "First Name", last_name "Last Name" FROM employees;
Making expressions readable
Aliases are most valuable on computed columns, where the database would otherwise generate an unhelpful default name like
?column? or an entire copy of the expression:Aliasing a computed column
SQL
SELECT product_name,
price * quantity AS total_price
FROM order_items;Quoting aliases with spaces
If an alias contains spaces or mixed case you want preserved, it needs to be quoted. Standard SQL and PostgreSQL use double quotes (
"First Name"), while MySQL by default uses backticks (`First Name`). SQL Server accepts either double quotes or square brackets ([First Name]). Unquoted aliases generally cannot contain spaces.Where you can (and can’t) use an alias
Aliases usually can't be used in WHERE
Because of SQL’s logical execution order,
WHERE runs *before* SELECT computes its column list — so at the point WHERE is evaluated, a SELECT alias does not exist yet. A query like this will typically fail with an “unknown column” error:This usually does NOT work
SQL
SELECT price * quantity AS total_price FROM order_items WHERE total_price > 100; -- error in most databases
To filter on that value, repeat the expression in
WHERE instead:Repeat the expression in WHERE
SQL
SELECT price * quantity AS total_price FROM order_items WHERE price * quantity > 100;
ORDER BY, on the other hand, runs *after* SELECT in the logical order, so it can freely reference a column alias:Aliases work fine in ORDER BY
SQL
SELECT price * quantity AS total_price FROM order_items ORDER BY total_price DESC;