← Back to PostgreSQL Course | Chapter 6: Joins | Lesson 5 of 7

CROSS JOIN

CROSS JOIN pairs every row of one table with every row of another.

In this page:

  1. CROSS JOIN
Syntax
sql
SELECT columns
FROM table1
CROSS JOIN table2;

CROSS JOIN

The result has rows(A) times rows(B) rows and no ON condition. It is useful for generating combinations such as sizes by colours. Accidental cartesian products from a missing join condition are a common performance bug.

Note: The row count is the product of both tables, so keep inputs small.

Example: CROSS JOIN

sql
CREATE TABLE sizes (size TEXT);
CREATE TABLE colors (color TEXT);
INSERT INTO sizes VALUES ('S'), ('M'), ('L');
INSERT INTO colors VALUES ('red'), ('blue');
SELECT size, color FROM sizes CROSS JOIN colors ORDER BY size, color;
SELECT COUNT(*) AS combinations FROM sizes CROSS JOIN colors;

-- Output:
-- size | color
-- L | blue
-- L | red
-- M | blue
-- M | red
-- S | blue
-- S | red
-- combinations
-- 6
Related Topics
Common Mistakes
  1. Forgetting the ON condition and creating a cross join accidentally
  2. Using it on big tables
  3. Expecting matches
Chapter Summary
  • CROSS JOIN pairs all rows
  • Result size is the product
  • No ON condition
  • Great for combinations
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.