An alias is a temporary name for a column or a table, given with AS. It lasts only for the query it appears in and changes nothing in the database.
SELECT column_name AS alias_nameFROM table_name AS table_alias;The examples use the tables from the example database.
Naming result columns
Section titled “Naming result columns”A column alias sets the heading of a column in the result. It matters most for columns that are worked out rather than read straight from the table, which would otherwise get an awkward heading or none at all:
SELECT Title AS Production, Budget / 1000000.0 AS BudgetMillionsFROM ProductionsWHERE Country = 'UK';| Production | BudgetMillions |
|---|---|
| The Lantern Keepers | 18.5 |
| Quarry Lane | 7.2 |
| Six Bells | 11.0 |
If an alias contains a space, put it in double quotes, or in square brackets in SQL Server and Access:
SELECT Name, DayRate AS "Day rate"FROM CrewWHERE Department = 'Camera';| Name | Day rate |
|---|---|
| Sam Ellis | 480 |
Joining text into one column
Section titled “Joining text into one column”An alias also names a column built from several others. To show each accountant’s name and role together:
SELECT Name || ' (' || Role || ')' AS CrewMemberFROM CrewWHERE Department = 'Accounts';| CrewMember |
|---|
| Tom Hale (Production Accountant) |
| Priya Nair (Assistant Accountant) |
| Lucy Brennan (Production Accountant) |
How you join text depends on the database:
| Database | Joining text |
|---|---|
| PostgreSQL, Oracle, SQLite | Name || ' (' || Role || ')' |
| SQL Server | Name + ' (' + Role + ')' |
| MySQL, and most others too | CONCAT(Name, ' (', Role, ')') |
Shortening table names
Section titled “Shortening table names”A table alias gives a table a short name for the rest of the query. It saves a lot of typing when columns from several tables have to be told apart:
SELECT i.InvoiceID, p.Title, i.AmountFROM Invoices AS iINNER JOIN Productions AS p ON i.ProductionID = p.ProductionIDWHERE p.Country = 'UK' AND i.Amount > 3000ORDER BY i.InvoiceID;| InvoiceID | Title | Amount |
|---|---|---|
| 1001 | The Lantern Keepers | 24,600.00 |
| 1002 | Quarry Lane | 3,180.00 |
| 1003 | The Lantern Keepers | 41,250.00 |
Once a table has an alias, the rest of the query refers to it by the alias. Oracle does not accept AS before a table alias, so FROM Invoices i is the form that works everywhere.