Aliases in SQL

In SQL queries, aliases are playing very important roles i.e you can change or give new column name in results or  you can give a new name for calculated column fields like sum of xyz. Like that you can use it tables or for queries. Lets see in details-

Aliases are mainly three types:-
  1. Column alias 
  2. Table alias 
  3. Query alias
1. Column Alias : Used for change or give new column name in result set-

Syntax:
SELECT <Column name> (AS Alias)
FROM <Table name>

Example:-

Here you can see result of this query- select "Hello SQL  is with no column name-

 

Lets define alias for this  query- select 'Hello SQL' as MyAlias and see result with as defined column name-

 

2. Table Alias : Used for following reasons : -
  1. To shorten the table name
  2. To remove ambiguity
  3. Easy to understand in Joins
Syntax:
Select  <Column name> (AS Alias)
FROM <Table name1> (AS Alias1),
<Table name2> (AS Alias2)

Example:-

Next is Table Alias so we can start with simple query with table alias-

SELECT [FirstName], [LastName]
  FROM [Person].[Person] as A




3. Query Alias : Used for sub-queries with desired name-

Syntax:
Select  ( Alias1). <Column name>
FROM
( Select  <Column name> FROM <Table name1> ) (AS Alias1)

Example:-

Here you can give a any name to your sub query and use it in main query-

Select A.FirstName 
From
(SELECT [FirstName],[LastName]
  FROM [Person].[Person]) as A


 

So you seen here how aliases are very helpful for designing queries. If you have any question regarding same please comment. Happy Coding