Cartesian ProductOptional for Informatics Practices
Every query so far named one table. Name two and something surprising happens: you do not get the tables side by side, you get every possible pairing of their rows. Understanding that is what makes a real join make sense.
1Two small tables
A school has two lab rooms and three teaching periods in the afternoon:
2Naming both tables
Put both names after from, separated by a comma, and no condition at all:
Two rooms and three periods gave six rows. Every room has been paired with every period: Lab A at period 1, Lab B at period 1, Lab A at period 2, and so on. Nothing has been added to either table — this is every combination that could be made from them.
The cartesian product pairs every row of the first table with every row of the second.
2 rows × 3 rows = 6 rows
Press the button and watch all six — then all twenty — pairings appear at once.
Every row of one table is paired with every row of the other first — the condition is what removes the nonsense afterwards.
| code | sname | id |
|---|---|---|
| CS083 | Computer Science | 2 |
| MA041 | Mathematics | 3 |
| PH042 | Physics | 9 |
| EN301 | English | 4 |
| HI302 | Hindi | NULL |
| id | name | designation |
|---|---|---|
| 2 | Mohan Das | PGT |
| 3 | Tashi Bhutia | TGT |
| 4 | Reena Gupta | TGT |
| 9 | Rajesh Kumar | PGT |
5 subjects × 4 teachers. Press Pair them up to see what the database actually builds.
No condition, so nothing is thrown away: 5 × 4 = 20 rows, most of them untrue. On the real twelve-row table that is 60. Multiply two thousand-row tables and it is a million.
3When this is what you want
Rarely — but not never. The six rows above are a genuine timetable grid: every slot that could be booked. If you were drawing a blank timetable to fill in, that is precisely the list you need.
4Why it is usually a mistake
Now try it with the real tables. Twelve teachers and five subjects:
Sixty rows — every teacher paired with every subject, including all the pairings that are simply untrue. Mohan Das appears alongside Hindi, which he does not teach. Only 5 of those 60 rows say anything correct.
5Other names for it
The same operation is called a cross join or an unrestricted join. In algebra it is written A × B, which is where “product” comes from. Your syllabus calls it the cartesian product; the others may appear in reference books.
6Recap
Every row of a paired with every row of b.
2 × 3 = 6 rows.
2 columns + 1 column = 3 columns.
Most of the pairings are meaningless. A where clause fixes it.
Table A has 4 rows and 3 columns; table B has 5 rows and 2 columns. What is the cardinality of their cartesian product?
What is the degree of the cartesian product of the same two tables?
A query on two tables returns far more rows than expected. What is the likely cause?