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:

  • 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:

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:

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.