Lecture

CROSS JOIN & SELF JOIN

SQL includes some advanced join types that are useful in specific scenarios:

  • CROSS JOIN: returns every possible pair of rows between two tables
  • SELF JOIN: joins a table to itself to compare rows within it

CROSS JOIN

A CROSS JOIN returns the Cartesian product of two tables, where every row in the first table is combined with every row in the second.

CROSS JOIN
SELECT students.name, days.day FROM students CROSS JOIN days;

Be cautious: the number of rows equals rows_in_students × rows_in_days, which can grow very quickly.

Use a CROSS JOIN when:

  • Generating all possible pairs (e.g., schedules, combinations)
  • Running pairwise comparisons
  • Creating grids or test cases

SELF JOIN

A SELF JOIN occurs when a table is joined with itself. This is useful for comparing or relating rows within the same table.

Example: Employees and Managers

Here is an example of a SELF JOIN on the employees table.

employees

idnamemanager_id
1AliceNULL
2Bob1
3Carol1
4Dave2

To find each employee's manager, use a SELF JOIN:

SELF JOIN to find managers
SELECT employees.name AS employee, managers.name AS manager FROM employees LEFT JOIN employees AS managers ON employees.manager_id = managers.id;

Result:

employeemanager
AliceNULL
BobAlice
CarolAlice
DaveBob

We use aliases (employees and managers) to distinguish the two roles of the same table.


Why use CROSS JOIN or SELF JOIN?

These joins are valuable in specialized cases:

  • CROSS JOIN → generating all possible matchups, building schedules, or creating grids/test cases
  • SELF JOIN → modeling hierarchical relationships, comparing rows within the same table, or linking employees to managers
Quiz
0 / 1

In SQL, a CROSS JOIN returns the Cartesian product of two tables, resulting in all possible pairs of rows between them.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result