PostgreSQL CROSS JOIN & Self Join
Two more join patterns complete the picture. A cross join combines every row of one table with every row of another. A self join joins a table to itself, which is how you work with hierarchies such as "employee and manager".
CROSS JOIN
A CROSS JOIN B returns every possible pair of rows, the Cartesian product. It has no ON condition. With 3 rows on one side and 2 on the other you get 3 × 2 = 6 rows:
CREATE TABLE formats (format text);
CREATE TABLE sizes (size text);
INSERT INTO formats VALUES ('paperback'), ('hardcover'), ('ebook');
INSERT INTO sizes VALUES ('standard'), ('large print');
SELECT format, size
FROM formats
CROSS JOIN sizes
ORDER BY format, size;CREATE TABLE
CREATE TABLE
INSERT 0 3
INSERT 0 2
format | size
-----------+-------------
ebook | large print
ebook | standard
hardcover | large print
hardcover | standard
paperback | large print
paperback | standard
(6 rows)
Cross joins are handy for generating combinations: every product variant, every day × every store, a price list for every quantity.
Cross join with generate_series
generate_series produces a sequence of values, and crossing it with a table creates a row per value. Price tables for 1 to 3 copies of the cheapest books:
SELECT b.title, q AS copies, b.price * q AS total
FROM books b
CROSS JOIN generate_series(1, 3) AS q
WHERE b.price < 9
ORDER BY b.title, q; title | copies | total
------------------+--------+-------
Moon Socks | 1 | 7.50
Moon Socks | 2 | 15.00
Moon Socks | 3 | 22.50
Ten Tiny Dragons | 1 | 8.99
Ten Tiny Dragons | 2 | 17.98
Ten Tiny Dragons | 3 | 26.97
(6 rows)
Note: Cross joins grow fast. Two tables of 10,000 rows each produce 100 million rows. Make sure a missing
ONcondition is intentional.
Self join: a table joined to itself
In employees, each row has a manager_id that points to another row of the same table. To list each employee with their manager's name, use the table twice with two different aliases:
SELECT e.name AS employee, e.job_title, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.id; employee | job_title | manager
----------------+---------------------+---------------
Rachel Adams | Managing Director |
Victor Chen | Store Manager | Rachel Adams
Nadia Hussein | Head of Online | Rachel Adams
Paul Becker | Bookseller | Victor Chen
Lucy Evans | Bookseller | Victor Chen
Omar Farouk | Web Developer | Nadia Hussein
Sara Lindqvist | Support Agent | Nadia Hussein
Tim Novak | Warehouse Assistant | Victor Chen
(8 rows)
Think of e and m as two copies of the table: one plays the employee, the other the manager. The left join keeps Rachel Adams, who has no manager.
Counting direct reports
Group the self join by the manager to see who manages how many people:
SELECT m.name AS manager, count(e.id) AS direct_reports,
string_agg(e.name, ', ' ORDER BY e.name) AS team
FROM employees m
JOIN employees e ON e.manager_id = m.id
GROUP BY m.id, m.name
ORDER BY direct_reports DESC, manager; manager | direct_reports | team
---------------+----------------+------------------------------------
Victor Chen | 3 | Lucy Evans, Paul Becker, Tim Novak
Nadia Hussein | 2 | Omar Farouk, Sara Lindqvist
Rachel Adams | 2 | Nadia Hussein, Victor Chen
(3 rows)
Comparing rows within a table
A self join can also compare rows of the same kind with each other. Which employees earn more than their own manager? (Nobody, thankfully.) And which pairs of customers live in the same city?
SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
SELECT a.first_name AS customer_1, b.first_name AS customer_2, a.city
FROM customers a
JOIN customers b ON a.city = b.city AND a.id < b.id; name | salary | manager | manager_salary
------+--------+---------+----------------
(0 rows)
customer_1 | customer_2 | city
------------+------------+-------
Ben | Olivia | Leeds
(1 row)
The condition a.id < b.id stops a customer being paired with themself, and avoids listing each pair twice (Ben–Olivia and Olivia–Ben).
Tip: A self join only reaches one level up or down. For the whole management chain (manager's manager's manager…), use a recursive CTE, shown in the CTE lesson.
Test yourself
A table with 4 rows is cross-joined with a table of 5 rows. How many rows result?
- 9
- 5
- 20
- 4
What do you need to join a table to itself?
- A special SELF JOIN keyword
- Two different aliases for the same table
- A copy of the table
- A view
Why use a.id < b.id when pairing customers from the same city?
- To sort the result
- To avoid self-pairs and duplicate mirrored pairs
- It is required by CROSS JOIN
- To use an index