PostgreSQL Aliases
Aliases let you give a column or table a temporary name for the duration of a query, making results easier to read and complex queries easier to write.
What Is an Alias?
An alias is a temporary label you assign to a column or a table using the AS keyword. The alias exists only for the lifetime of the query and does not change the underlying schema. Aliases are especially useful when a column name is long, when you compute a new value with an expression, or when you need to distinguish between two copies of the same table in a self-join.
Column Aliases
A column alias renames the output header of a SELECT list item. This is purely cosmetic for the result set: it changes what the client sees in the returned columns, not the table itself.
Alias a Column
SELECT first_name AS "First Name",
last_name AS "Last Name"
FROM employees;Table Aliases
A table alias gives a shorter or more descriptive name to a table reference, which is invaluable once a query touches more than one table. Instead of repeating a long table name in every column reference, you prefix columns with the short alias.
Alias a Table
SELECT e.first_name, e.salary
FROM employees AS e
WHERE e.salary > 50000;Aliases with Expressions
Aliases are almost mandatory when a column is the result of a calculation, a function call, or a concatenation, since PostgreSQL would otherwise label it with an unhelpful auto-generated name like ?column?.
Alias a Computed Column
SELECT first_name || ' ' || last_name AS full_name,
salary * 12 AS annual_salary
FROM employees;- Column aliases rename output headers only, not stored column names.
- Table aliases shorten references and are required for self-joins.
- Quoted aliases ("Full Name") preserve spaces and mixed case.
- Aliases cannot be used in the WHERE clause of the same SELECT (only in ORDER BY or GROUP BY, and only sometimes).
Exercise: PostgreSQL Aliases
Is the AS keyword required to create a column alias in PostgreSQL?