Sub topic 2
Why Aliases Matter When a Table Appears Twice
This chapter assumes you can write SELECT queries with WHERE and ORDER BY, and that you know how INNER JOIN and LEFT JOIN use an ON condition. You should also know what primary keys and foreign keys are. Nothing here needs more than that.
A normal join combines two different tables, so each table name points to exactly one thing. A self join combines a table with itself, and that breaks the one-name-one-thing rule. Aliases fix it. This chapter covers the alias syntax, the scoping rules, and the errors you get when aliases are missing or misused. Later chapters build full self join queries on top of it.
The sample data
The examples use a table where each row points to another row in the same table through manager_id.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INT REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2);Ava has no manager, so her manager_id is NULL. Ben and Chen report to Ava. Dana reports to Ben.
The problem: one name, two roles
To list each employee next to their manager, you need two rows from employees at once. One row plays the employee and the other plays the manager. A first attempt might look like this:
SELECT name, name
FROM employees
INNER JOIN employees ON manager_id = id;This fails. The database sees two row sources with the same name, employees, and cannot tell which one name, manager_id, or id refers to. Each system rejects it in its own wording:
| System | Typical error |
|---|---|
| PostgreSQL | `table name "employees" specified more than once` |
| MySQL | `Not unique table/alias: 'employees'` |
| SQL Server | `The objects "employees" and "employees" in the FROM clause have the same exposed names` |
The missing piece is a second name. An alias gives each use of the table its own name inside one query.
What a table alias is
A table alias is a temporary name for a row source. It exists only for the duration of one query and changes nothing in the database. You write it right after the table name in the FROM clause:
SELECT e.name
FROM employees AS e;The AS keyword is optional in most systems, so FROM employees e means the same thing. Oracle is the exception. It rejects AS before a table alias, so write FROM employees e if you need to run on Oracle. The form without AS works everywhere, which is why many teams use it for table aliases.
Once you alias a table, the alias is its name for the rest of that query. Each occurrence of the table in FROM gets its own alias, and the database treats the occurrences as independent row sources:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
ORDER BY e.id;The result:
| employee | manager |
|---|---|
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
Ava is missing because her manager_id is NULL, and NULL = m.id is never true. Keeping her in the result is the job of a LEFT JOIN, which a later chapter covers.
How to picture it
Think of the table being read twice, with each copy given a role. The alias e is the employee copy and m is the manager copy. The ON condition links a row in one copy to a row in the other.
The database stores only one copy of the data. The two aliases are two independent views of the same rows, and the optimizer can match them in any order it finds cheapest. The aliases name the roles in your query. They do not make a physical copy.
Qualified column names
Both aliases expose every column of the table, so e has id, name, and manager_id, and so does m. An unqualified column name now matches two columns, and the database refuses to guess:
SELECT name
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id;This fails with an ambiguity error. The wording differs by system:
- PostgreSQL:
column reference "name" is ambiguous - MySQL:
Column 'name' in field list is ambiguous - SQL Server:
Ambiguous column name 'name' - SQLite:
ambiguous column name: name
The fix is to qualify every column with its alias, as in e.name and m.id. Qualify even the columns that look unambiguous. In ON e.manager_id = m.id, the plain name manager_id would still run, but prefixing every column makes the query readable. You can then tell at a glance which role each column belongs to.
Direction matters: which alias goes on which side
The aliases are symmetric from the database's point of view, so it is your ON condition that gives them meaning. Compare these two conditions:
-- e is the employee, m is that employee's manager
ON e.manager_id = m.id
-- e is the manager, m is one of that manager's direct reports
ON m.manager_id = e.idBoth are valid. If you keep the column labels from the first query but use the second condition, the result is wrong without any error. The labels say employee and manager while the data says the reverse. A safer habit is to choose alias names that state the role, then check the output against rows you know:
SELECT mgr.name AS manager, emp.name AS direct_report
FROM employees emp
INNER JOIN employees mgr ON emp.manager_id = mgr.id
ORDER BY mgr.id, emp.id;Here the child row carries the foreign key (emp.manager_id) and the parent row carries the key it points to (mgr.id). That pattern holds for every parent-child join.
Aliases scale to more levels
When the same table appears three times, you need three aliases. This query follows the chain from an employee up two levels:
SELECT e.name AS employee,
m.name AS manager,
g.name AS grand_manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
INNER JOIN employees g ON m.manager_id = g.id;With the sample data, only Dana has two levels above her, so the result has one row: Dana, Ben, Ava. Each extra level needs another alias and another join, which is the limit that the last chapter on recursive queries addresses.
Scope rules
Where you can use an alias depends on which clause you are in.
- A table alias is defined in
FROMand visible everywhere in the same query block:ON,WHERE,GROUP BY,HAVING,SELECT, andORDER BY. - A column alias, such as
AS employee, is defined inSELECT. Standard SQL lets you use it inORDER BYbut not inWHERE,GROUP BY, orHAVING, because those clauses are evaluated beforeSELECT. Some systems relax this, so do not rely on it if you want portable code. - Alias names must be unique within one
FROMclause. Two aliases namedein the same block cause the same "not unique" error you saw earlier. - A subquery has its own scope. It can see aliases from the outer query, but the outer query cannot see the subquery's aliases.
This WHERE clause shows the first rule. It filters on the manager role, not the employee role:
SELECT e.name AS employee
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
WHERE m.name = 'Ava'
ORDER BY e.id;It returns Ben and Chen. Changing m.name to e.name would ask a different question, namely which employees are named Ava and have a manager, and the result would be empty.
Aliases are not only for self joins
Aliases also appear in other places, which is useful to know when you read other people's queries:
- Derived tables, which are subqueries in
FROM, must have an alias in MySQL and in PostgreSQL before version 16. WriteFROM (SELECT ...) AS recent. - Long table names are easier to read when shortened.
order_line_items oliis quicker to scan than repeating the full name. - Quoted aliases, such as
AS "Direct Report", keep their case and spaces. Use them for output labels, but avoid them for table aliases because every reference must then be quoted the same way.
Choosing alias names
Short names work for a small query, but a clear role name saves time when someone else reads it later.
| Situation | Suggested aliases | Reason |
|---|---|---|
| Employee and manager | `emp`, `mgr` | The names state the role |
| Two symmetric rows being compared | `a`, `b` | Neither row has a special role |
| Three or more levels | `e`, `m`, `g` or `emp`, `mgr`, `gmgr` | Keep the order of the chain visible |
| Different tables | initials such as `st`, `p` | Short and unique |
Avoid reserved words as alias names, and avoid reusing one alias for different tables in nested queries, even where the rules allow it.
Checklist for any query with a repeated table
- Give every occurrence of the table its own alias.
- Qualify every column with an alias, in
SELECT,ON,WHERE, andORDER BY. - Put the foreign key on the child alias and the primary key on the parent alias.
- Label output columns with
ASso the roles are visible in the result. - Check the result against a few rows you can verify by hand.
Exercise
Using the employees table from this chapter, write a query that lists each manager and the name of each direct report, with the manager's name in a column called manager and the report's name in a column called directreport. Use the aliases mgr and emp, and order by the report's id. Which rows come back, and why is Ava not in the directreport column?
Show answer
SELECT mgr.name AS manager, emp.name AS directreport FROM employees emp INNER JOIN employees mgr ON emp.managerid = mgr.id ORDER BY emp.id; The rows are Ava with Ben, Ava with Chen, and Ben with Dana. Ava is not in the directreport column because her managerid is NULL, so the condition emp.manager_id = mgr.id is never true for her and the inner join drops her row as a report.
Exercise
A colleague runs SELECT name FROM employees e INNER JOIN employees m ON e.manager_id = m.id; and gets an ambiguity error. Explain the cause and give two valid fixes, one that returns the employee names and one that returns the manager names.
Show answer
Both aliases e and m expose a column called name, so the unqualified name matches two columns and the database cannot choose. Qualify the column with an alias. SELECT e.name FROM employees e INNER JOIN employees m ON e.managerid = m.id; returns the employees (Ben, Chen, Dana). SELECT m.name FROM employees e INNER JOIN employees m ON e.managerid = m.id; returns the managers (Ava, Ava, Ben), one row per employee who has a manager.
Exercise
Extend the grand manager query so that the third alias is used in a WHERE clause to return only employees whose grand manager is named Ava. What does it return for the sample data, and what happens if you write WHERE employees.name = 'Ava' instead?
Show answer
Add WHERE g.name = 'Ava' to the three-alias query. For the sample data it returns one row: Dana, Ben, Ava. Writing WHERE employees.name = 'Ava' fails in most systems (PostgreSQL reports invalid reference to FROM-clause entry for table "employees") because the original table name is hidden once every occurrence of the table has an alias.