PostgreSQL – Alias
The PostgreSQL Alias is used to assign a temporary name to a table or a column in a query. They only exist at the time of the query execution.
Below Syntax is for column alias:
SELECT column_name AS alias_name FROM table; or, SELECT column_name alias_name FROM table;
Below Syntax is for column alias used with expressions:
SELECT expression alias_name FROM table;
The primary use of column alias is to make the output of a query more meaningful.
The below example illustrates the use of column alias:
Here we will make a query to get full name of the customers from the “customer” table using column alias.
SELECT first_name || ' ' || last_name AS full_name FROM customer ORDER BY full_name;
Below Syntax is for table alias:
SELECT column_list FROM table_name AS alias_name; or, SELECT column_list FROM table_name alias_name;
There are multiple use-cases for table alias. Few of them are listed below:
- It can be used to save some keystrokes and make your query more readable for tables with long names.
- It can also be used when you query data from multiple tables that have the same column names.
- It can be used to join a table with itself (ie, SELF JOIN).
The below example illustrates the use of table alias:
Here we will be using table alias to avoid writing “address” for each column instead use a short form “add” as an alias to get the “district” and “postal_code” column from the “address” table of our database.
SELECT add.postal_code, add.district FROM address add;