Chapter 6 · Lesson 7 of 7

CROSS JOIN for All Combinations

Generate every combination of rows from two tables with CROSS JOIN, such as each department paired with each meeting day.

CROSS JOIN returns every possible combination of rows from both tables.

If one table has 4 rows and the other has 2, the result has 8 rows.

SELECT d.name AS department_name, m.day_name
FROM departments AS d
CROSS JOIN meeting_days AS m

CROSS JOIN is useful for generating schedules, calendars, test cases, and other complete combinations. Be careful though: the result size grows very quickly.

Sample data

This lesson loads the departments + meeting_days tables into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for departments, meeting_days
CREATE OR REPLACE TABLE departments (
    id INTEGER,
    name VARCHAR
  );

INSERT INTO departments VALUES
    (1, 'Engineering'),
    (2, 'Marketing'),
    (3, 'Sales'),
    (4, 'Support');

CREATE OR REPLACE TABLE meeting_days (
    day_name VARCHAR
  );

INSERT INTO meeting_days VALUES
    ('Tuesday'),
    ('Thursday');

Practice challenge

Create every department/day combination. Return department_name and day_name, ordered by department_name and day_name.

Hint: Use CROSS JOIN between departments and meeting_days.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in JOIN Types

Combine related tables with INNER, LEFT, RIGHT, FULL OUTER, SELF, and CROSS JOIN, and find rows that have no match.

  1. 01 · Why JOINs Exist
  2. 02 · INNER JOIN Basics
  3. 03 · LEFT JOIN Keeps the Left Side
  4. 04 · Finding Missing Matches
  5. 05 · RIGHT JOIN and FULL OUTER JOIN
  6. 06 · SELF JOIN for Hierarchies
  7. 07 · CROSS JOIN for All Combinations

Related guides