SQL Alias

What is an Alias?

An Alias is a shorthand for a table or column name.
Aliases reduce the amount of typing required to enter a query.

Complex queries with Aliases are generally easier to read.
Aliases are useful with JOINs and aggregates: SUM, COUNT, etc.
An Alias only exists for the duration of the query.


The SQL Alias syntax

The general syntax is

SELECT column-name AS alias-name
  FROM table-name alias-name
 WHERE condition

CUSTOMER
Id
FirstName
LastName
City
Country
Phone

SQL Alias Examples

Problem: List total customers in each country.
Display results with easy to understand column headers.
SELECT COUNT(C.Id) AS TotalCustomers, C.Country AS Nation
  FROM Customer C
 GROUP BY C.Country

TotalCustomers and Nation are column Aliases.
The table Alias (C) in this example is not particularly useful.

Result:  21 records
TotalCustomers Nation
3 Argentina
2 Austria
2 Belgium
9 Brazil
3 Canada

CUSTOMER
Id
FirstName
LastName
City
Country
Phone
ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: List the total amount ordered by customer
with easy to read column headers
SELECT C.Id AS Identifier, C.LastName + ', ' + C.FirstName AS CustomerName, 
       SUM(O.TotalAmount) AS TotalSpent
  FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id
 GROUP BY C.Id, C.LastName + ', ' + C.FirstName
 ORDER BY TotalSpent DESC

The Aliases significantly simplify writing the JOIN and ORDER BY clauses.
The C Alias in C.Id helps identify the Customer Id rather then the Order Id.

Results: 89 records
Identifier CustomerName TotalSpent
63 Kloss, Horst 117483.39
71 Pavarotti, Jose 115673.39
20 Mendel, Roland 113236.68
37 McKenna, Patricia 57317.39
65 Wilson, Paula 52245.90


Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas