Open In App

PostgreSQL – Alias

Last Updated : 03 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

PostgreSQL aliases are powerful tools that allow you to assign temporary names to tables or columns within your queries. These aliases only exist during the execution of the query, making your SQL code more readable and efficient.

What is a PostgreSQL Alias?

An alias in PostgreSQL is a temporary name given to a table or column. This can help simplify complex queries, improve readability, and make it easier to reference tables and columns.

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 Aliases in PostgreSQL

Column aliases allow you to rename the columns in the result set of your query, making the output more meaningful.

Syntax

SELECT column_name AS alias_name FROM table;

or,

SELECT column_name alias_name FROM table;

You can also use column aliases 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: Using Column Aliases

Here we will make a query to get full name of the customers from the “customer” table using column alias.

Query:

SELECT
first_name || ' ' || last_name AS full_name
FROM
customer
ORDER BY
full_name;

Output:

Explanation: This query concatenates the ‘first_name’ and ‘last_name’ columns into a single ‘full_name’ column for better readability.

Table Aliases in PostgreSQL

Table aliases provide a way to shorten table names in your queries, especially useful for tables with long names or when joining multiple tables.

Syntax

SELECT column_list FROM table_name AS alias_name;

or,

SELECT column_list FROM table_name alias_name;

Use Cases

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).

Example: Using Table Aliases

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.

Query:

SELECT add.postal_code,
add.district
FROM address add;

Output:

Explanation: This query uses ‘add’ as an alias for the ‘address’ table, making the query shorter and easier to read.



Next Article
Practice Tags :

Similar Reads