Sub topic 4
Table aliases and qualified column names
This chapter assumes you can write basic SELECT, FROM, WHERE and ORDER BY queries. It also assumes you know what primary keys and foreign keys are, and that you have seen a basic INNER JOIN ... ON query. The examples use the customers and orders tables from the sample schema, plus employees and order_items where noted.
Why joins need qualified names
Once a query reads from two tables, a column name can belong to either one. Both customers and orders have a column called id. If you write this, the database cannot know which id you mean:
SELECT id, name, total
FROM customers
INNER JOIN orders ON customer_id = id;PostgreSQL stops with column reference "id" is ambiguous. MySQL, SQL Server and Oracle give similar errors. The database does not guess. It refuses to run the query.
A qualified column name fixes this. It has the form table.column:
SELECT customers.name, orders.id, orders.total
FROM customers
INNER JOIN orders ON orders.customer_id = customers.id;Every reference to id now says which table it comes from. This version runs and returns the three matching rows.
Table aliases
Writing the full table name everywhere gets long. A table alias gives a table a short name for the duration of one query. You put the alias after the table name, with or without the AS keyword:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;Here c stands for customers and o stands for orders. The result is the same as the long form. Most style guides recommend writing AS because it makes the alias easy to spot. Oracle does not accept AS before a table alias, so omit it there: FROM customers c.
An alias is local to the query that defines it. It does not rename anything in the database, and a different query can use c for another table.
Rules that catch people out
- Once you alias a table, the original name is hidden. In PostgreSQL and most other databases,
FROM customers AS cmeanscustomers.nameis an error. Usec.nameeverywhere in that query, including inWHERE,GROUP BYandORDER BY. - An alias must be unique within its
FROMclause. Two tables cannot both be calledo. - Aliases for tables are defined in
FROM, so they work in every other clause. This differs from column aliases (AS order_id), which the standard does not let you use inWHERE.
When you must qualify and when you may
You must qualify a column only when its name exists in more than one table in the query. In the example above, name exists only in customers and total only in orders, so these would work unqualified. id exists in both, so it must be qualified.
Do not rely on that, though. Consider qualifying every column in a join query, for two reasons:
- Readability. A reader can see which table each column comes from without checking the schema.
- Stability. Suppose someone later adds a
totalcolumn tocustomers. An unqualifiedtotalthat worked yesterday now fails with an ambiguity error. Qualified names are not affected.
Single-table queries do not need qualification. Adding it there is optional.
Naming the output columns
Qualification affects how you refer to a column inside the query. It does not always change the name in the result. A result column takes the bare column name, so selecting both c.id and o.id gives two columns that are both labeled id:
SELECT c.id, o.id
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;Many client tools show two columns named id. Some drivers that return rows as dictionaries keep only one of them, and the other value is silently lost. Add column aliases to give each a distinct label:
SELECT c.id AS customer_id, o.id AS order_id
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;Choosing good aliases
Short aliases are convenient, but they should still be meaningful. Common conventions:
| Convention | Example | Comment |
|---|---|---|
| First letter of the table | `c` for `customers` | Quick, but clashes when two tables start with the same letter |
| Initials of a multi-word name | `oi` for `order_items` | Works well for snake_case names |
| Role-based name | `e`, `m` for employee and manager | Required clarity when a table appears twice |
| Meaningless sequence | `t1`, `t2`, `t3` | Avoid. The reader must look back at `FROM` to decode each one |
In the three-table query from the previous chapters, c, o, i and p are enough because each name is distinct and obvious.
One table, two roles
Aliases are not only a convenience. Sometimes they are the only way to write the query. When a table is joined to itself, the two copies need different names, or the database cannot tell them apart:
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
INNER JOIN employees AS m ON m.id = e.manager_id;The same employees table appears twice, once as e (the person) and once as m (that person's manager). Without the aliases, employees.id would be ambiguous. Self joins get their own chapter. For now, note that this is the case where aliases are mandatory.
Derived tables, meaning subqueries in FROM, also need an alias in many databases. PostgreSQL requires one, and so does MySQL:
SELECT big.customer_id, big.total
FROM (
SELECT customer_id, total
FROM orders
WHERE total > 30
) AS big;Common errors and what they mean
The error text varies by database, but the causes are consistent.
| Symptom | Likely cause | Fix |
|---|---|---|
| `column reference "id" is ambiguous` | An unqualified column exists in more than one joined table | Prefix it with a table alias |
| `missing FROM-clause entry for table "customers"` | You aliased the table, then used its original name | Use the alias everywhere |
| `column c.nme does not exist` | A typo after a correct alias | Check the column spelling against the schema |
| `table name "o" specified more than once` | Two tables share one alias | Give each a distinct alias |
| `Every derived table must have its own alias` | A subquery in `FROM` has no alias | Add `AS some_name` after the closing parenthesis |
A subtler mistake is qualifying with the wrong alias. The query ON o.customer_id = o.id is valid, because both columns exist in orders. It silently compares an order's customer to the order's own id, and it returns wrong rows with no error. When a join returns surprising results, check each ON condition and confirm that it uses one alias on each side.
How the database reads an alias
The diagram shows the order in which the names become available. The FROM clause defines the aliases first. Every other clause is then resolved against them.
This is a simplification of the logical processing order. It shows why a table alias is visible everywhere. A column alias created in SELECT is defined late, which is why WHERE cannot see it in standard SQL.
Exercises
Exercise
This query fails with an "ambiguous column" error. Rewrite it so that it runs and returns both ids under distinct labels. SELECT id, id, total FROM customers INNER JOIN orders ON customer_id = id;
Show answer
Alias the tables, qualify every column, and label the two ids: SELECT c.id AS customerid, o.id AS orderid, o.total FROM customers AS c INNER JOIN orders AS o ON o.customer_id = c.id; Both tables have an id column, so each must be qualified. Without the column aliases, the result would have two columns both named id.
Exercise
A query contains FROM orders AS o INNER JOIN customers AS c ON o.customer_id = c.id WHERE orders.total > 30. Why does it fail, and what is the fix?
Show answer
Once orders is aliased as o, the name orders is no longer available in that query, so orders.total is an error. Change the filter to o.total > 30.
Exercise
Why can the query SELECT e.name, m.name FROM employees AS e INNER JOIN employees AS m ON m.id = e.manager_id not be written without aliases, and what problem remains in its output?
Show answer
The same table appears twice, so aliases are the only way to tell the two roles apart. The output problem is that both result columns are labeled name. Add column aliases, for example e.name AS employee and m.name AS manager.