Advertisement
Google Ad Slot: content-top
MySQL CROSS JOIN
MySQL CROSS JOIN
A CROSS JOIN in MySQL produces the Cartesian product of two tables.
- It combines every row from the first table with every row from the second table.
- If the first table has
mrows and the second table hasnrows, the result will havem × nrows. - Unlike other joins, CROSS JOIN does not require a join condition using
ON.
CROSS JOIN Syntax
SELECT table1.column_name, table2.column_name FROM table1 CROSS JOIN table2;
Example Scenario:
Consider two tables:
Students Table:
student_id |
name |
gender |
city |
age |
score |
course_id |
phone_number |
|
|---|---|---|---|---|---|---|---|---|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
Courses Table:
course_name |
course_name |
|---|---|
101 |
Math |
102 |
Science |
103 |
History |
104 |
English |
The following SQL statement selects all students, and all courses:
Explanation:
- The
CROSS JOINkeyword returns all matching records from both tables whether the other table matches or not. So, if there are rows in "Students" that do not have matches in "Courses", or if there are rows in "Courses" that do not have matches in "Students", those rows will be listed as well.