Self Joins, Cross Joins and Non-Equi Joins in SQL
Three joins that go beyond matching a foreign key to a primary key: self joins for relationships inside one table, CROSS JOIN for every combination of two sets, and non-equi joins that match rows by ranges, bands, dates and inequalities, including triangular joins and how fast they grow.
kvi5hnuCode Sprout team member10 min readOn this page
Most joins compare a foreign key with the primary key it references (article 12). This article covers three other shapes that solve everyday problems:
- Self joins join a table to itself, for relationships between rows of the same table.
- Cross joins pair every row of one table with every row of another.
- Non-equi joins match rows with conditions other than equality, such as ranges.
The examples use the shop database from article 12. Each example creates the extra tables it needs.
Self joins
The customers table has a referred_by column that holds the customer_id of the customer who referred them. It's a foreign key that references the same table. To show each customer's referrer by name, the query has to read customers twice: once for the customer and once for the referrer. Giving the table two different aliases makes that possible:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Self join: each customer with the customer who referred them
SELECT c.name AS customer, r.name AS referred_by
FROM customers c
LEFT JOIN customers r ON r.customer_id = c.referred_by
ORDER BY c.customer_id;
-- Pairs of customers in the same city, each pair listed once
SELECT a.city, a.name AS first_customer, b.name AS second_customer
FROM customers a
JOIN customers b ON b.city = a.city
AND b.customer_id > a.customer_id
ORDER BY a.city, a.name;
customer | referred_by
--------------+-------------
Asha Rao | (null)
Ben Okafor | Asha Rao
Chen Wei | Asha Rao
Dana Cruz | Ben Okafor
Eli Novak | (null)
Farah Haddad | Chen Wei
(6 rows)
city | first_customer | second_customer
-------+----------------+-----------------
Leeds | Ben Okafor | Eli Novak
Pune | Asha Rao | Chen Wei
(2 rows)

A self join is an ordinary join. The database treats c and r as two separate inputs that happen to hold the same rows. The aliases are required, because without them every column reference would be ambiguous. Choose names that say what role each copy plays, such as c and r, emp and mgr, or child and parent.
The first query uses a LEFT JOIN so that customers without a referrer (Asha and Eli) still appear. An inner join would silently drop them.
Pairs within one table
The second query finds pairs of customers who live in the same city. Two details matter:
b.customer_id > a.customer_idstops a customer from pairing with themselves, and lists each pair once. With<>instead, both (Asha, Chen) and (Chen, Asha) would appear.- Farah's city is NULL, so
b.city = a.cityis never true for Farah, not even when compared with Farah. Rows with NULL never join on equality.
Self joins handle one level of a relationship: a customer and their direct referrer, or an employee and their direct manager. To follow a chain of any length, such as "everyone Asha referred, directly or indirectly", you need a recursive query (article 25).
Cross joins
CROSS JOIN pairs every row of the first table with every row of the second. Two tables with m and n rows give m × n rows. There's no join condition. This is the Cartesian product that a forgotten join condition produces by accident (article 12), but sometimes it's exactly what you want:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- CROSS JOIN: every combination of two small lists
CREATE TABLE sizes (size VARCHAR(2) PRIMARY KEY, size_order INTEGER);
CREATE TABLE colours (colour VARCHAR(10) PRIMARY KEY);
INSERT INTO sizes VALUES ('S', 1), ('M', 2), ('L', 3);
INSERT INTO colours VALUES ('charcoal'), ('forest');
SELECT c.colour, s.size, 'SOCK-' || upper(left(c.colour, 3)) || '-' || s.size AS sku
FROM colours c
CROSS JOIN sizes s
ORDER BY c.colour, s.size_order;
-- A grid of every customer city and every order status, ready to be filled with counts
SELECT DISTINCT c.city, st.status
FROM customers c
CROSS JOIN (VALUES ('pending'), ('shipped'), ('delivered')) AS st(status)
WHERE c.city IS NOT NULL
ORDER BY c.city, st.status;
colour | size | sku
----------+------+------------
charcoal | S | SOCK-CHA-S
charcoal | M | SOCK-CHA-M
charcoal | L | SOCK-CHA-L
forest | S | SOCK-FOR-S
forest | M | SOCK-FOR-M
forest | L | SOCK-FOR-L
(6 rows)
city | status
-------+-----------
Leeds | delivered
Leeds | pending
Leeds | shipped
Pune | delivered
Pune | pending
Pune | shipped
York | delivered
York | pending
York | shipped
(9 rows)
- Generating combinations. Two colours and three sizes give six product variants, each with a generated SKU. Cross joins are a natural way to generate test data, price lists or calendars.
- Building a grid for a report. The second query lists every (city, status) combination, including combinations with no orders. A report that left-joins its counts onto this grid shows zeros, instead of leaving out the empty cells (Part 4). The
VALUESlist inFROMacts as a small inline table, called a table value constructor.
a CROSS JOIN b means the same as the comma form FROM a, b without a WHERE condition, and the same as a JOIN b ON TRUE. Write CROSS JOIN when you mean it, so readers know the missing condition is deliberate.
Be careful with sizes. Cross joins grow multiplicatively: a cross join of three tables with 1,000 rows each produces a billion rows.
Non-equi joins
A non-equi join has a join condition that isn't simple equality: <, >, BETWEEN, <> or any other comparison. The most common use is matching values to ranges stored in another table:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Non-equi join: match each product to a shipping band by weight
CREATE TABLE shipping_bands (
band VARCHAR(10) PRIMARY KEY,
min_g INTEGER NOT NULL,
max_g INTEGER NOT NULL, -- inclusive
fee DECIMAL(6, 2) NOT NULL
);
INSERT INTO shipping_bands VALUES
('letter', 0, 249, 2.50),
('small', 250, 1999, 4.90),
('large', 2000, 9999, 9.90);
SELECT p.name, p.weight_g, b.band, b.fee
FROM products p
JOIN shipping_bands b ON p.weight_g BETWEEN b.min_g AND b.max_g
ORDER BY p.weight_g;
-- Date ranges: which promotion was running when each order was placed?
CREATE TABLE promotions (code VARCHAR(10), starts_on DATE, ends_on DATE); -- ends_on exclusive
INSERT INTO promotions VALUES ('SPRING', DATE '2026-03-01', DATE '2026-03-08'),
('EQUINOX', DATE '2026-03-18', DATE '2026-03-22');
SELECT o.order_id, o.placed_on, pr.code
FROM orders o
LEFT JOIN promotions pr ON o.placed_on >= pr.starts_on AND o.placed_on < pr.ends_on
ORDER BY o.order_id;
name | weight_g | band | fee
-------------------+----------+--------+------
Merino socks | 80 | letter | 2.50
Glow head torch | 90 | letter | 2.50
Day 18 backpack | 640 | small | 4.90
Trail 30 backpack | 1150 | small | 4.90
Ridge 2 tent | 2100 | large | 9.90
Summit 4 tent | 4300 | large | 9.90
(6 rows)
order_id | placed_on | code
----------+------------+---------
101 | 2026-03-02 | SPRING
102 | 2026-03-05 | SPRING
103 | 2026-03-09 | (null)
104 | 2026-03-15 | (null)
105 | 2026-03-20 | EQUINOX
106 | 2026-03-22 | (null)
(6 rows)
Matching values to bands
The first query looks up a shipping band for each product by weight, using p.weight_g BETWEEN b.min_g AND b.max_g. This is more flexible than a CASE expression (article 11). The bands are data, so they can change without changing the query, and other queries can reuse them.
Two things can go wrong with range tables:
- Gaps. A value that falls in no range has no match, and an inner join drops it. The Basecamp lantern has no weight, so it matched no band and isn't in the result. Use a
LEFT JOINif every row must appear. - Overlaps. A value that falls in two ranges matches twice, so the row is duplicated. If one band ended at 250 and the next started at 250, a 250 g product would appear twice. Make the ranges either inclusive at both ends and contiguous (0–249, 250–1999), or half-open (
>= min AND < max). Half-open ranges are safer for decimals and timestamps, where "the next value" isn't well defined.
Matching dates to periods
The second query uses half-open date ranges: each promotion runs from starts_on up to, but not including, ends_on. Orders 101 and 102 fall in the SPRING promotion, and order 105 falls in EQUINOX. The LEFT JOIN keeps the orders that fall in no promotion. The same pattern matches transactions to exchange rates by date, prices to the price list valid at the time, or employees to the department they belonged to on a given day.
PostgreSQL also has range types, such as daterange, with operators for containment (@>) and overlap (&&), and it can prevent overlapping ranges with an exclusion constraint. Other products use pairs of columns, as in this example.
Triangular joins
A non-equi self join compares rows of one table with each other:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Each product with every cheaper product in the same category (a "triangular" join)
SELECT a.category, a.name, b.name AS cheaper_option, a.price - b.price AS saving
FROM products a
JOIN products b ON b.category = a.category
AND b.price < a.price
ORDER BY a.category, a.name;
-- How fast triangular joins grow: n rows give n * (n - 1) / 2 pairs
SELECT n, (SELECT COUNT(*) FROM generate_series(1, n) x JOIN generate_series(1, n) y ON y < x) AS pairs
FROM (VALUES (10), (100), (1000)) AS t(n);
category | name | cheaper_option | saving
----------+-------------------+------------------+--------
lighting | Glow head torch | Basecamp lantern | 7.50
packs | Trail 30 backpack | Day 18 backpack | 35.95
tents | Summit 4 tent | Ridge 2 tent | 239.01
(3 rows)
n | pairs
------+--------
10 | 45
100 | 4950
1000 | 499500
(3 rows)
The first query pairs each product with every cheaper product in the same category. Because each row is compared with the rows "below" it, this shape is called a triangular join. It's the pre-window-function way of computing ranks and running totals: "count the products cheaper than this one" gives a rank, and "sum the amounts of all earlier rows" gives a running total.
The second query shows the cost. With n rows, a triangular join produces about n² / 2 pairs: 4,950 for 100 rows, but 499,500 for 1,000 and about 500 billion for a million. For ranks and running totals, use window functions instead (Part 6). They do the same job in a single pass over sorted rows.
How non-equi joins perform
Hash joins (article 12) only work with equality, so non-equi joins usually run as nested loops, which compare each row on one side with many rows on the other. An index on the range column, such as shipping_bands(min_g), can help each lookup. For a small band or calendar table, the cost doesn't matter. For two large tables, check the plan (article 67), and look for an equality condition you can add, such as matching on category as well as price.
What's current
- SQL added temporal tables with periods and
FOR PORTION OF, which help with the date-range pattern. Support varies: Db2, MariaDB, Oracle (partially) and SQL Server (system-versioned tables) implement parts of it. - PostgreSQL 18 added temporal constraints:
PRIMARY KEYandUNIQUEconstraints withWITHOUT OVERLAPS, and foreign keys withPERIOD, so the database can enforce non-overlapping date ranges declaratively.
Common questions
Is a self join a special kind of join? No. It's a normal inner or outer join where both inputs are the same table. The aliases make the two copies distinguishable.
How do I avoid pairing a row with itself in a self join?
Add a condition on the key: b.id <> a.id keeps both orders of each pair, and b.id > a.id keeps each pair once.
When would I ever want a cross join? To generate combinations (variants, schedules, test data), to build a complete grid for a report so that empty cells show as zeros, or to attach a single-row result, such as a total or a settings row, to every row.
Is CROSS JOIN the same as a join without a condition?
Yes. FROM a CROSS JOIN b, FROM a, b and FROM a JOIN b ON TRUE all give every combination where the database has a TRUE literal (SQL Server needs ON 1 = 1). Some products reject JOIN without ON, so CROSS JOIN is the clear, portable spelling.
Can a non-equi join be an outer join?
Yes. LEFT JOIN bands ON value BETWEEN low AND high keeps the values that fall in no band, with NULL band columns.
Why does my range join return duplicate rows?
The ranges overlap, so some values match more than one range. Check the range table for overlaps, and use half-open ranges (>= low AND < high) so that boundaries belong to exactly one range.
Summary
- A self join reads one table twice with two aliases, for relationships between rows of the same table, such as referrers or managers.
- Use a
LEFTself join to keep rows that have no related row. Useb.id > a.idto list each pair once. CROSS JOINreturns every combination of rows, m × n of them. Use it on purpose, for combinations and report grids, and watch the sizes.- Non-equi joins match on
BETWEEN,<,>and other conditions, typically to look up bands or date periods. - Range tables must have no gaps (or use a
LEFT JOIN) and no overlaps. Half-open ranges avoid boundary problems. - Triangular self joins grow with the square of the row count. Use window functions for ranks and running totals.
Practice questions
Write a query that shows each customer's name together with the names of the customers they referred, including customers who referred nobody.
Answer
SELECT r.name AS referrer, c.name AS referred_customer
FROM customers r
LEFT JOIN customers c ON c.referred_by = r.customer_id
ORDER BY r.name, c.name;
This time the preserved side is the referrer, r, and the join finds the customers whose referred_by points to them. Asha appears twice (Ben and Chen), Ben once (Dana), Chen once (Farah), and Dana, Eli and Farah once each, with NULL, because they referred nobody.
A tiers table has rows (bronze, 0, 100), (silver, 100, 500) and (gold, 500, 100000) for min_spend and max_spend. A query joins customers to tiers with total_spend BETWEEN t.min_spend AND t.max_spend. What happens to a customer who spent exactly 100, and how do you fix it?
Answer
BETWEEN includes both ends, so 100 falls in both bronze (0–100) and silver (100–500), and the customer appears twice. Use half-open ranges, total_spend >= t.min_spend AND total_spend < t.max_spend, so each boundary value belongs only to the higher tier.
How many rows does SELECT * FROM products CROSS JOIN customers return in the shop database, and how many does SELECT * FROM products p JOIN customers c ON TRUE return?
Answer
Both return 7 × 6 = 42 rows. ON TRUE is a join condition that's always true, so every combination is kept, which is exactly a cross join.
Write a query that returns, for each product, the number of products in the same category that are cheaper than it, using a self join. Why is this approach a poor choice for large tables?
Answer
SELECT a.name, a.category, COUNT(b.product_id) AS cheaper_in_category
FROM products a
LEFT JOIN products b ON b.category = a.category
AND b.price < a.price
GROUP BY a.product_id, a.name, a.category
ORDER BY a.category, a.name;
The LEFT JOIN keeps the cheapest product in each category with a count of 0, and COUNT(b.product_id) counts only real matches (GROUP BY is covered in Part 4). The query compares every product with every other product in its category, so the work grows with the square of the category size. A window function, RANK() OVER (PARTITION BY category ORDER BY price) - 1, gives the same numbers in one sorted pass (article 27).
Previous: SQL Outer Joins: LEFT, RIGHT and FULL JOIN
Next: SQL Set Operations: UNION, UNION ALL, INTERSECT and EXCEPT

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.