SQL AS Keyword
The AS
keyword in SQL is used to create aliases (alternative names) for columns or tables. Aliases make your queries more readable and easier to understand, especially when dealing with complex queries involving joins or multiple tables.
Using AS: Aliases for Columns
Simple Column Aliases
This example creates aliases for 'CustomerID' and 'CustomerName'.
Syntax
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Output
ID | Customer
---------------
(CustomerID values) | (CustomerName values)
Aliases with Spaces
To use aliases with spaces, you need to enclose them in square brackets or double quotes.
Syntax
SELECT CustomerName AS Customer, ContactName AS "Contact Person"
FROM Customers;
Output
Customer | Contact Person
------------------------
(CustomerName values) | (ContactName values)
Creating an Alias from Multiple Columns
This example combines multiple columns ('Address', 'PostalCode', 'City', 'Country') into a single alias named 'Address'.
Syntax
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
--MySQL Equivalent:
SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers;
Output
CustomerName | Address
----------------------------------------------------
(CustomerName values) | (Concatenated address information)
Using AS: Aliases for Tables
Table Aliases in a Join
This shows how to use table aliases ('c' for 'Customers' and 'o' for 'Orders') to shorten a query.
Syntax
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName = "Around the Horn" AND c.CustomerID = o.CustomerID;
Output
OrderID | OrderDate | CustomerName
-------------------------------------
(Order IDs) | (Order Dates) | Around the Horn (repeated for each order)