SQL Aliases - The Coding Shala

Home >> Learn SQL >> SQL Aliases

SQL Aliases

SQL Aliases are used to give a temporary name to the table or a column. By using Aliases we can change the name of columns or tables to make them more readable. These changes are temporary, the actual table name does not change in the database. The alias only exists for the duration of the query. Aliases are two types - column alias and table alias.
SQL Aliases - The Coding Shala

SQL Aliases column syntax

The basic SQL column Aliases syntax is as follows - 

 SELECT column_name AS alias_name  
 FROM table_name;

SQL Aliases Table Syntax

The basic SQL Table Aliases syntax is as follows - 

 SELECT column_name(s)  
 FROM table_name AS alias_name; 

SQL Aliases Examples 

The following 'emp' and 'Persons' two tables are used for the examples - 
 Id     Name     Age     Address     Salary  
 1     Akshay     22     Pune        40000  
 2     Mohit      21     Delhi       42000  
 3     Akash      21     Delhi       45000  
 4     Nikhil     24     Mumbai      50000  
 5     Smith      24     Pune        50000  
 6     Akshay     22     Pune        50000  
 7     Nikhil     24     Mumbai      43000  

 PersonID     LastName     FirstName     Address     City  
 1            Saini         Akshay        A-101     Pune  
 2            last         first          A-101     Pune  
 3            Smith         Jhon           B-02     Mum 

The following example shows the uses of Table Alias - 

SQL >> select p.PersonID, e.Name, e.Age, p.City  
       from Persons p, emp e  
       where p.PersonID = e.ID;  
Output >>   
 PersonID     Name     Age     City  
 1           Akshay     22     Pune  
 2           Mohit      21     Pune  
 3           Akash      21     Mum  

The Same Query can be written using 'as' - 

SQL >>select p.PersonID, e.Name, e.Age, p.City  
       from Persons as p, emp as e  
       where p.PersonID = e.ID; 

The following example shows the uses of Column Alias - 

SQL >>select PersonID ID, FirstName "EMPLOYEE NAME", City CITY  
       from Persons;  
Output >>  
 1        Akshay          Pune  
 2        first           Pune  
 3        Jhon            Mum  

If your alias name is containing space, then you have to write it in the double quote (" ") otherwise it will give the error like "Alias Name". 

Other Posts You May Like
Prev<< SQL Joins                                                                                           NEXT >>SQL Comments
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala