Self-joins and cross joins

Topic 3 of 4 in Joining tables11 min readBeginnerFree course

Overview

The joins so far connected two different tables. Two more kinds complete the picture: a self-join, which joins a table to itself, and a cross join, which pairs every row of one table with every row of another. Both sound odd at first, and both solve problems nothing else does neatly.

Self-joins: one table, two roles

The employees table has a manager_id column pointing at another row of the same table:

SQL
SELECT id, name, title, manager_id
FROM employees
ORDER BY id;
Text
 id |    name     |       title        | manager_id 
----+-------------+--------------------+------------
  1 | Maya Singh  | CEO                |           
  2 | Tom Hughes  | Head of Operations |          1
  3 | Lina Costa  | Head of Marketing  |          1
  4 | Raj Mehta   | Warehouse Lead     |          2
  5 | Sofia Rossi | Support Agent      |          2
  6 | Omar Haddad | Marketing Analyst  |          3
  7 | Nina Berg   | Packer             |          4
(7 rows)

To show each employee next to their manager’s name, you need to read the table twice: once as “the employee” and once as “the manager”. Aliases make that possible — the same table appears in FROM twice, under two names:

Self-join: a table joined to itself. employees AS e has rows Tom Hughes (manager_id 1), Raj Mehta (manager_id 2) and Nina Berg (manager_id 4). employees AS m has rows 1 Maya Singh, 2 Tom Hughes and 4 Raj Mehta. Arrows connect each e row to the m row whose id equals its manager_id. The query SELECT e.name, m.name AS manager FROM employees AS e LEFT JOIN employees AS m ON m.id = e.manager_id returns Maya Singh with manager NULL, Tom Hughes with manager Maya Singh, and Nina Berg with manager Raj Mehta. Aliases (e, m) let the same table play two roles. LEFT JOIN keeps Maya, who has no manager.

SQL
SELECT e.name AS employee, e.title, m.name AS manager
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
ORDER BY e.id;
Text
  employee   |       title        |  manager   
-------------+--------------------+------------
 Tom Hughes  | Head of Operations | Maya Singh
 Lina Costa  | Head of Marketing  | Maya Singh
 Raj Mehta   | Warehouse Lead     | Tom Hughes
 Sofia Rossi | Support Agent      | Tom Hughes
 Omar Haddad | Marketing Analyst  | Lina Costa
 Nina Berg   | Packer             | Raj Mehta
(6 rows)

Everything works exactly like a normal join — the database doesn’t care that e and m are the same table. The aliases are essential, though: without them, employees.name would be ambiguous.

Notice Maya is missing. As the CEO she has no manager, so the inner join found no partner for her. A LEFT JOIN keeps her:

SQL
SELECT e.name AS employee,
       COALESCE(m.name, '— (top of the company)') AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.id = e.manager_id
ORDER BY e.id;
Text
  employee   |        manager         
-------------+------------------------
 Maya Singh  | — (top of the company)
 Tom Hughes  | Maya Singh
 Lina Costa  | Maya Singh
 Raj Mehta   | Tom Hughes
 Sofia Rossi | Tom Hughes
 Omar Haddad | Lina Costa
 Nina Berg   | Raj Mehta
(7 rows)

Once each row sits next to its “parent”, you can compare them. Who earns more than 60% of their manager’s salary?

SQL
SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary,
       round(100.0 * e.salary / m.salary) AS pct_of_manager
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
WHERE e.salary > 0.6 * m.salary
ORDER BY pct_of_manager DESC, e.name;
Text
    name     | salary |  manager   | manager_salary | pct_of_manager 
-------------+--------+------------+----------------+----------------
 Tom Hughes  |  98000 | Maya Singh |         150000 |             65
 Lina Costa  |  95000 | Maya Singh |         150000 |             63
 Nina Berg   |  39000 | Raj Mehta  |          62000 |             63
 Raj Mehta   |  62000 | Tom Hughes |          98000 |             63
 Omar Haddad |  58000 | Lina Costa |          95000 |             61
(5 rows)

You can chain the self-join to go up more levels — join a third copy, employees AS mm ON mm.id = m.manager_id, to get the manager’s manager:

SQL
SELECT e.name, m.name AS manager, mm.name AS managers_manager
FROM employees AS e
JOIN employees AS m  ON m.id  = e.manager_id
JOIN employees AS mm ON mm.id = m.manager_id
ORDER BY e.id;
Text
    name     |  manager   | managers_manager 
-------------+------------+------------------
 Raj Mehta   | Tom Hughes | Maya Singh
 Sofia Rossi | Tom Hughes | Maya Singh
 Omar Haddad | Lina Costa | Maya Singh
 Nina Berg   | Raj Mehta  | Tom Hughes
(4 rows)

That’s the question from the chapter 1 exercise, answered in one query. But each extra level needs another join, and you don’t always know how deep a hierarchy goes. For a whole tree of any depth, you’ll use a recursive CTE in Common table expressions.

Finding pairs

A self-join can also match rows that share something. Which customers live in the same city as another customer?

SQL
SELECT a.first_name AS customer, b.first_name AS neighbour, a.city
FROM customers AS a
JOIN customers AS b ON b.city = a.city
                   AND b.id <> a.id
ORDER BY a.city, a.first_name;
Text
 customer | neighbour | city 
----------+-----------+------
 Asha     | Farhan    | Pune
 Farhan   | Asha      | Pune
(2 rows)

b.id <> a.id stops each customer matching themselves. But each pair appears twice — Asha with Farhan, and Farhan with Asha. To list each pair once, use < instead:

SQL
SELECT a.first_name AS first, b.first_name AS second, a.city
FROM customers AS a
JOIN customers AS b ON b.city = a.city
                   AND a.id < b.id;
Text
 first | second | city 
-------+--------+------
 Asha  | Farhan | Pune
(1 row)

The same trick finds products at the same price, orders placed on the same day, or — very usefully — duplicate records that differ only in their id:

SQL
SELECT a.id, b.id AS duplicate_id, a.email
FROM customers AS a
JOIN customers AS b ON lower(b.email) = lower(a.email)
                   AND a.id < b.id;
Text
 id | duplicate_id | email 
----+--------------+-------
(0 rows)

No duplicates — the UNIQUE constraint on email sees to that. On real-world imported data, a query like this is often the first thing you run.

CROSS JOIN: every combination

A cross join has no ON condition: it pairs every row of the first table with every row of the second, so the result has rows × rows rows. That’s also called a Cartesian product.

Suppose Bean & Leaf starts selling teas in three pack sizes, with the list price being the price per 100 g. Every tea in every size is a cross join with a small list of sizes:

SQL
SELECT p.name, s.grams, round(p.price * s.grams / 100, 2) AS pack_price
FROM products AS p
CROSS JOIN (VALUES (50), (100), (250)) AS s(grams)
WHERE p.category_id = 2
ORDER BY p.name, s.grams;
Text
          name          | grams | pack_price 
------------------------+-------+------------
 Assam Breakfast        |    50 |       4.75
 Assam Breakfast        |   100 |       9.50
 Assam Breakfast        |   250 |      23.75
 Chamomile Calm         |    50 |       4.00
 Chamomile Calm         |   100 |       8.00
 Chamomile Calm         |   250 |      20.00
 Darjeeling First Flush |    50 |       9.00
 Darjeeling First Flush |   100 |      18.00
 Darjeeling First Flush |   250 |      45.00
 Jasmine Green          |    50 |       6.38
 Jasmine Green          |   100 |      12.75
 Jasmine Green          |   250 |      31.88
(12 rows)

Four teas × three sizes = twelve rows. (VALUES (50), (100), (250)) AS s(grams) is a small table written inline — handy for lists like this without creating a real table.

Cross joins are the standard way to build grids you’ll fill in later. Every category for every quarter, ready for a LEFT JOIN of sales figures so that empty cells show up as zero:

SQL
SELECT c.name AS category, q.quarter
FROM categories AS c
CROSS JOIN generate_series(1, 4) AS q(quarter)
WHERE c.id <= 2
ORDER BY c.name, q.quarter;
Text
 category | quarter 
----------+---------
 Coffee   |       1
 Coffee   |       2
 Coffee   |       3
 Coffee   |       4
 Tea      |       1
 Tea      |       2
 Tea      |       3
 Tea      |       4
(8 rows)

The accidental cross join

Cross joins become a problem when you get one without meaning to. Forget the join condition in the old comma style, and every row pairs with every row:

SQL
SELECT count(*) AS rows_returned
FROM orders, customers;
Text
 rows_returned 
---------------
           240
(1 row)

24 orders × 10 customers = 240 meaningless rows. On real tables — a million orders and a hundred thousand customers — that’s 100 billion rows, and a query that never finishes. A wrong join condition (ON o.customer_id = o.customer_id, say) has the same effect. When a join result is suspiciously large, look for a missing or broken ON.

Tip: with JOIN … ON, PostgreSQL refuses a join with no condition — you have to write CROSS JOIN deliberately. That’s one more reason to prefer the explicit style.

Exercise

Who manages whom?

Using a self-join on employees, list every manager with the number of people who report directly to them. Return the manager's name as manager and the count as direct_reports, sorted by direct reports (most first) and then by manager name. Only people who manage someone should appear — Maya Singh and Tom Hughes have two reports each, Lina Costa and Raj Mehta one each.

SQL
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id;

Summary

  • A self-join joins a table to itself; give each copy its own alias so they can play different roles.
  • Self-joins follow references inside one table, such as employees.manager_id → employees.id.
  • Use LEFT JOIN in a self-join to keep rows with no parent — like the CEO, who has no manager.
  • Self-joins with a condition like a.id < b.id find pairs of related rows without duplicates.
  • CROSS JOIN returns every combination of rows (rows × rows); it's useful for grids and calendars, and dangerous by accident.