SQL Aliases

Aliases in SQL

  • SQL aliases are often used to give a temporary name to a column of a table or an enitre table.
  • Generally aliases used to make the selected column names more readable in query result.
  • The lifespan of an alias is small, it only exists during execution of query.

Alias Column Syntax

SELECT column_name1 AS alias_name1, column_name2 as alias_name2,....
FROM table_name;
There is no need to specify alias name for all columns in the select list.

Alias Table Syntax

SELECT column_name1, column_name2, .... , column_nameN
FROM table_name AS alias_name;

Alias Column Example

The following SQL query is used to select the first name of all the students.
SELECT first_name AS name FROM student_details;
In the above query, the column first_name is given an alias as 'name'. Now instead of first_name 'name' will be printed in the output.

Output

  name  
--------
 Carol
 Sam
 Daryl
 Morgan
 Rick
(5 Rows)

Alias Table Example

 SELECT s.last_name FROM student as s;  
In the above query, alias 's' is defined for the table student and the column last_name is selected from the table.

Output

postgres=> select student.last_name from s as student; 
 last_name 
-----------
 Dentist
 Wick
 Dixon
 Dee
 Grimes
(5 rows)

Aliases can be more useful when:

  • The column names are not readable or very lengthy
  • More than one tables need to be used in an SQL query.
  • Functions are used in the query
  • More than one columns are combined together
Pre - SQL SELECT Statement Next - SQL WHERE Clause

Comments