Table Aliases
Just like a column can be given a temporary name with
AS, a table can be given a short, temporary name too. Table aliases barely matter for a query with a single table, but they become essential the moment more than one table is involved.Basic syntax
Aliasing a table
SQL
SELECT u.id, u.name FROM users AS u;
As with column aliases, the word
AS is optional in most databases — FROM users u works exactly the same way as FROM users AS u.Why this matters once JOINs show up
The real value of a table alias appears once a query reads from more than one table at a time, which is extremely common once you start using
JOIN. If two tables both have a column called id or created_at, the database (and the reader) needs a way to know which table’s column you mean. Aliases give every column reference a short, unambiguous prefix:Disambiguating columns with aliases (a preview of JOINs)
SQL
SELECT o.id AS order_id,
c.name AS customer_name,
o.created_at
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.id;Here
o and c make it instantly clear which table each column comes from, and keep the query far shorter than repeating orders.id and customers.name everywhere. We will cover joins themselves in detail later in this series.Self-joins: aliasing the same table twice
Table aliases are not just a convenience — they are required when a query needs to refer to the same table more than once, such as comparing employees to their own managers within a single
employees table:Self-join using two aliases for one table
SQL
SELECT e.name AS employee_name,
m.name AS manager_name
FROM employees AS e
JOIN employees AS m ON e.manager_id = m.id;Without the aliases
e and m, there would be no way to tell the two references to employees apart — the database would not know which copy of the table name refers to in each part of the query.Aliases make queries shorter and easier to read once multiple tables are involved
They remove ambiguity when two tables share a column name
They are the only way to reference the same table twice in one query (a self-join)
Naming convention
Short, meaningful aliases (often the first letter or two of the table name, like
o for orders or c for customers) are the most common style, though any valid identifier works.