Understand Column Alias in Select Query in SQL Server - SQL Server / TSQL Tutorial Part 115

Scenario:


You are working as SQL Server developer, you need to extract the data from dbo.Customer table and provide in an Excel Sheet. Your table has difference columns such as FName, LName but you want the output to come with FirstName and LastName. How would you do that?

Solution:

Alias is a great way to make your column names more readable. As in our question above, we want to display FName as FirstName and LName as LastName, Alias is the way to go. Let's create dbo.Customer table with columns and then use select query with alias to display Columns as we like.

Create table dbo.Customer
 (Id int,
  FName VARCHAR(50),
  LName VARCHAR(50))
GO
insert into dbo.Customer
Values (
1,'Raza','M'),
(2,'Rita','John')



To create Alias you can use "AS" after column name or simply provide the alias right after column name. In below query, I have use "as" for FName but did not use for LName.

Select FName as FirstName,
LName LastName
From dbo.Customer

How to use Alias in SQL Server to Rename Column for output - SQL Server / TSQL Tutorial

If you would like to have space between your Alias Column Name such as "First Name". You can use [ ] around the alias or double quotes e.g "First Name".

Select FName as [First Name],
LName as "Last Name"
From dbo.Customer

How to use Alias in SQL Server - SQL Server / TSQL Tutorial


No comments:

Post a Comment