Alias example
SELECT c.name AS customer,
ROUND(SUM(p.total), 2) AS total_amount
FROM customers AS c
INNER JOIN orders AS p
ON p.customer_id = c.id
WHERE c.id IN (1, 3)
GROUP BY c.id, c.name
ORDER BY total_amount DESC;c and p shorten references to tables. customer e total_amount name the columns that whoever uses the result will see.
Check the result with small data
We work out the value of each sales line.
WITH sales(units, price) AS (
VALUES (2,5), (1,9)
)
SELECT units * price AS amount
FROM sales ORDER BY amount DESC;| amount |
|---|
| 10 |
| 9 |
AS amount names the expression in the output and lets you sort by that label. It does not create a permanent column called amount in sales.
Check your understanding: Which part of the query would you change to call it subtotal?
Show answer
Only the alias: change AS amount to AS subtotal and, since ORDER BY uses that name, also change ORDER BY amount to ORDER BY subtotal. The expression units * price and the data stay the same.
How aliases are used
AS makes it clear that a column is being named. Many engines let you leave it out, and table aliases vary in style and syntax; keeping it where the engine allows makes the query easier to read.
Common mix-ups with aliases
Still using a table's original name
After writing FROM customers AS c, use c.name. In PostgreSQL, the alias replaces the table name within that query, so customers.name is no longer a valid reference.
Avoid cryptic aliases in long queries. A single letter may be enough for two familiar tables; with many tables, names such as cli and ped may be clearer.
Two kinds of alias with different scopes
A table alias identifies a source during the query; a column alias names a result. In c.name AS customer, c lets you find the input column and customer labels its output. Neither renames the stored table or changes the data. Telling those two roles apart helps you make sense of “name does not exist” errors.
A derived table or a CTE can turn an output alias into a column available to the outer query. That new scope explains why a calculated name can be filtered on outside, even though it should not be used in the WHERE of the same layer. Do not adopt one universal rule for every grouping use: engines differ, and the alias can also clash with original column names.
To avoid ambiguity, do not give a calculated expression the same name as an input column with a different meaning. An amount including tax should not share its name with the base amount. In exports, use stable, unique names; in queries meant for reading, clarity matters more than abbreviating every name. When the same table appears twice, an alias for each role becomes essential so the condition compares the right people.
Technical questions: PostgreSQL: SELECT, columns and aliases (opens in a new tab).