Open In App

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.

For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.



Column Alias

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:

Example 1:
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;

Output:

Table Alias

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:

The below example illustrates the use of table alias:

Example 2:
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;

Output:

Article Tags :