Friday, April 9, 2010

Database Testing - SQL Lesson 4 - SQL Alias

Previous12345678910

SQL Alias

SQL Alias is used to make a column more readable when the output is displayed. They are defined for columns and tables. Instead of displaying the column name we use an Alias to bring in more meaning.


For Example: Instead of displaying the column header for an output as ‘First_Name” it is better to display as First Name. Since the column names are already created when the table is created and would be difficult to modify them because of the constraint it is better to give a meaningful name in the query.

Aliases given for columns:


The query can be written in either ways.

SELECT first_name as First Name from EmployeeDetails;
or
SELECT first_name as First Name from EmployeeDetails;


Look at this query this would really give you a clear picture of Alias.

We want to join the first and last name from the EmployeeDetails table.

SELECT FirstName + ' ' + LastName from dbo.EmployeeProfile;


If we write the query like this then it will display full names but the name of the column will not be meaningful.

Output:

No Column Name
-------------
Ravi Kumar
Rahul Patil
Sania Mirza

Now if you rewrite your query using an SQL Alias then it will be readable.

SELECT FirstName + ' ' + LastName as 'Full Name' from dbo.EmployeeProfile

Output:

Full Name
----------

Ravi Kumar
Rahul Patil
Sania Mirza


Aliases given for Tables:


Aliases are more useful when we have to deal with multiple tables or columns which are having difficult names to understand. Look at the below

1. If more than one table is involved in the query.
2. If functions are used in a query.
3. If the column names are big or not understood.

Example:

SELECT e.FirstName from EmployeeDetails e;

From the above query it is understood that e is referred to the table EmployeeDetails and the FirstName is taken from the EmployeeDetails table.

Previous12345678910

No comments:

Post a Comment