MySQL Aliases
MySQL Aliases
An alias is created with the AS keyword, and
is often used to make a column name more readable.
An alias only exists for the duration of that query.
Alias for Column Syntax
SELECT column_name AS alias_name
FROM table_name;Alias for Table Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
| 4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
| 5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
Alias for Columns
The following SQL creates two aliases, one for the CustomerID column and one for the CustomerName column:
Alias with Spaces
If you want your alias to contain one or more spaces, like "Contact Person", surround the aliasname with single or double quotes:
Example
SELECT CustomerName AS Customer, ContactName AS "Contact Person"
FROM Customers;
Try it Yourself »
Concatenate Columns
The following SQL creates an alias named "Address" that combine four columns (Address, PostalCode, City and Country):
Example
SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City, Country)
AS Address
FROM Customers;
Try it Yourself »
Alias for Tables
The following SQL selects all the orders from the customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter):
Example
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;
Try it Yourself »
The following SQL is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;
Try it Yourself »
Aliases are useful when:
- There are more than one table involved in a query
- Functions are used in the query
- Column names are long or not very readable
- Two or more columns are combined together