Careeroza
Aliases
SQL Aliases
An alias gives a column or table a temporary name for the duration of the query, written with AS. Aliases make results readable and long queries shorter.
-- column alias
SELECT column_name AS alias_name FROM table_name;
-- table alias
SELECT column_name(s) FROM table_name AS alias_name;Column Aliases
Example
Give the ID and name columns shorter, friendlier names:
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;Result: 8 rows
| ID | Customer |
|---|---|
| 1 | Aarav Traders |
| 2 | Blue Harbor Foods |
| 3 | Cedar & Co |
| 4 | Delta Mart |
… 4 more rows
Note: AS is optional for column aliases in most databases (SELECT CustomerID ID), but writing it is clearer.
Aliases with Spaces
Example
If the alias contains spaces, quote it with double quotes (or [ ] in SQL Server):
SELECT ProductName AS "Product Name", Price * Stock AS "Stock Value"
FROM Products;Result: 6 rows
| Product Name | Stock Value |
|---|---|
| Basmati Rice 5kg | 1500 |
| Green Tea 100 bags | 2025 |
| Olive Oil 1L | 799.2 |
| Dark Chocolate | 0 |
| Espresso Beans 1kg | 810 |
| Almonds 500g | NULL |
Concatenate Columns
Example
Combine first and last name into one column. SQLite, PostgreSQL and Oracle use ||:
SELECT FirstName || ' ' || LastName AS FullName, Department
FROM Employees;Result: 6 rows
| FullName | Department |
|---|---|
| Rahul Verma | Sales |
| Sara Khan | Sales |
| David Lee | Sales |
| Ananya Iyer | Support |
| James Taylor | Support |
| Fatima Ali | Finance |
-- MySQL
SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM Employees;
-- SQL Server
SELECT FirstName + ' ' + LastName AS FullName FROM Employees;Table Aliases
Example
Table aliases keep joins short (joins are covered in the Medium level):
SELECT o.OrderID, c.CustomerName
FROM Orders AS o, Customers AS c
WHERE o.CustomerID = c.CustomerID AND c.Country = 'India';Result: 4 rows
| OrderID | CustomerName |
|---|---|
| 101 | Aarav Traders |
| 102 | Delta Mart |
| 104 | Aarav Traders |
| 107 | Delta Mart |