SQL Aliases
Learn via video course
Overview
As the name suggests, alias is a keyword in SQL which is used as a temporary name for a table or column, while writing a query. Giving aliases makes the table or column name more readable and is also preferred when there are a lot of queries written for a table.
What is an Alias in SQL Statements?
Alias in SQL is basically a temporary name that is given to a table or a column while writing a query. This is usually done when the column or the table names are long, so in order to render more readability, alias is given. The alias in SQL is a temporary change and only exists till the duration of that query.
In SQL alias, when we rename a table name or a column name, the actual table name or column name does not get changed. Aliasing is preferred when there are a lot of queries written for a table.
Column alias is used to make the column heading more readable while the table alias is used to make the table name more readable.
Syntax for Column Alias
In the above syntax, we can see that we have given an alias for the column name.
Syntax for Table Alias
In the above syntax, we can see that we have given an alias for the table name.
For using an alias in SQL, we use the keyword "as" or "AS".
Examples
Consider the following table named "India_Offices".
Office_id_India | Location | Target_Area | Employees | Global_Rank |
---|---|---|---|---|
81 | Bangalore | Sales | 748 | 89 |
37 | Pune | Software | 349 | 34 |
67 | Hyderabad | Cloud | 2999 | 898 |
78 | Noida | Marketing | 28 | 76 |
19 | Chennai | Hardware | 82 | 477 |
Now we will understand the alias clause by using queries on the above table.
How to Alias a Column Name?
So, we will write a query that will fetch us the Office_id_India column.
Query
Output
o_id |
---|
81 |
37 |
67 |
78 |
19 |
How to Alias a Table Name?
Consider another table named "Managers". Now we are joining two tables using a common attribute and writing a query for it.
Office_id | Emp_id | Manager_name |
---|---|---|
81 | 88 | Prince Chandila |
37 | 679 | Adhya Rathi |
67 | 1089 | Dipti Kadam |
78 | 999 | Deepak Rai |
19 | 1893 | Jay Bhagat |
Query
Output
Office_id | Target_Area | Manager_name |
---|---|---|
81 | Sales | Prince Chandila |
37 | Software | Adhya Rathi |
67 | Cloud | Dipti Kadam |
78 | Marketing | Deepak Rai |
19 | Hardware | Jay Bhagat |
We can see that the table names have been aliased and used here.
Conclusion
- Alias in SQL is basically a temporary name that is given to a table or a column while writing a query.
- Giving aliases makes the table or column name more readable.
- It is preferred when there are a lot of queries written for a table.
- In SQL alias, when we rename a table name or a column name, the actual table name or column name does not get changed. It is a temporary change and only exists till the duration of that query.
- We can give an alias for a table name or a column name.