PostgreSQL - Alias

PostgreSQL

In this tutorial we will be creating alias for columns and tables in PostgreSQL.

We use alias to give new temporary name to columns and tables. Alias remains till the query executes.

This tutorial uses the employee table. To learn how to create a table check out this tutorial PostgreSQL - CREATE Table.

Do also read PostgreSQL - Select using WHERE clause tutorial on how to select rows from tables using filters.

Employee Table

SELECT * FROM employee;


 employeeId | firstName | lastName | score |   lastModifiedAt    |      createdAt      |  birthday  |        email
------------+-----------+----------+-------+---------------------+---------------------+------------+----------------------
 e01        | Yusuf     | Shakeel  |     0 | 2018-02-04 06:08:10 | 2021-01-01 01:01:01 | 1900-01-01 | yusuf@example.com
 e04        | Tin       | Tin      |     7 | 2018-02-04 06:08:10 | 2018-01-01 01:02:03 | 1900-10-20 | tintin@example.com
 e05        | Bob       | Coder    |     7 | 2018-02-04 06:08:10 | 2018-01-01 01:02:10 | 1900-08-20 | bobcoder@example.com
 e02        | John      | Doe      |     9 | 2018-02-04 06:08:10 | 2018-01-01 01:01:04 | 1900-02-03 | johndoe@example.com
 e03        | Jane      | Doe      |     9 | 2018-02-04 06:08:10 | 2018-01-01 01:01:04 | 1900-05-20 | janedoe@example.com
(5 rows)

Alias syntax for column

SELECT column_name AS alias_name FROM table_name;

In the following example we are going to give an alias id to the column employeeId of the employee table.

SELECT "employeeId" AS id, "firstName", "lastName" FROM employee;


 id  | firstName | lastName
-----+-----------+----------
 e01 | Yusuf     | Shakeel
 e04 | Tin       | Tin
 e05 | Bob       | Coder
 e02 | John      | Doe
 e03 | Jane      | Doe
(5 rows)

Alias syntax for table

SELECT tbl.column_name FROM table_name tbl;

In the following example we are going to give the employee table an alias e.

SELECT e."employeeId", e."firstName", e."lastName" FROM employee e;


 employeeId | firstName | lastName
------------+-----------+----------
 e01        | Yusuf     | Shakeel
 e04        | Tin       | Tin
 e05        | Bob       | Coder
 e02        | John      | Doe
 e03        | Jane      | Doe
(5 rows)