SQL Aliases
SQL aliases provide temporary, alternative names for tables or columns within a single query. They make your SQL more readable and easier to understand, particularly in complex queries.
Creating Aliases
Using the AS Keyword
Aliases are created using the AS
keyword. While the AS
keyword is often used, it's actually optional in many database systems.
Syntax (with AS)
SELECT column_name AS alias_name
FROM table_name;
Example: Simple Column Alias
Syntax
SELECT CustomerID AS ID FROM Customers;
Output
ID
--
(CustomerID values from the Customers table)
Optional AS Keyword
The AS
keyword is optional in many database systems. This shorter syntax achieves the same result:
Syntax
SELECT CustomerID ID FROM Customers;
Output
ID
--
(CustomerID values from the Customers table)
Aliases with Spaces
If your alias needs spaces, enclose it in square brackets []
or double quotes ""
.
Syntax
SELECT ProductName AS "My Great Product" FROM Products; --Using double quotes
SELECT ProductName AS [My Great Product] FROM Products; --Using square brackets
Output
My Great Product
-----------------
(ProductName values from the Products table)
Creating Aliases for Tables
The same AS
keyword is used to create aliases for tables. This is particularly useful when joining multiple tables.
Syntax
SELECT column_name(s) FROM table_name AS alias_name;
Example: Table Alias
Syntax
SELECT * FROM Customers AS Persons;
Output
(All columns and rows from the Customers table will be displayed.)
Combining Columns into a Single Alias
This creates an alias 'Address' by combining several columns. (Assumes a 'Customers' table with 'Address', 'PostalCode', 'City', and 'Country' columns).
Syntax (SQL Server)
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
Syntax (MySQL)
SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers;
Syntax (Oracle)
SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ', ' || Country) AS Address
FROM Customers;
Output
CustomerName | Address
-------------------------------------------------
(Customer names and their combined address information)
Table Aliases in a JOIN
Using aliases to shorten a query involving two tables ('Customers' and 'Orders'). (Assumes 'Customers' and 'Orders' tables exist with linking columns).
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
-----------------------------------
(Orders for 'Around the Horn' will be displayed here.)