Search code examples
mysqljoinselectcross-join

MySQL - JOIN without ON clause vs CROSS JOIN vs SELECT t1.* t2.* FROM t1, t2;


My question is. Are there any scenarios that below three queries would produce different output? Will they always return the same data set or are they any exceptions. Also are they any difference in performance?

It seems that in all cases row from one table is multiplied by row from another table.

JOIN (WITHOUT "ON" CLAUSE)

SELECT * FROM 
t1 JOIN t2;

CROSS JOIN

SELECT * FROM t1 
CROSS JOIN t2;

SELECT FROM TWO TABLES

SELECT a.*, b.*
FROM t1 a, t2 b;

Example data:

CREATE TABLE t1(id integer, t CHAR(2));
INSERT INTO t1(id, t) 
VALUES
  (1, "t1"),
  (2, "t1"),
  (3, "t1"),
  (NULL, "t1")
;

CREATE TABLE t2(id integer, t CHAR(2));
INSERT INTO t2(id, t) 
VALUES
  (2, "t2"),
  (3, "t2"),
  (4, "t2"),
  (NULL, "t2")
;

All queries will produce the same output:

+------+------+------+------+
| id   | t    | id   | t    |
+------+------+------+------+
|    1 | t1   |    2 | t2   |
|    2 | t1   |    2 | t2   |
|    3 | t1   |    2 | t2   |
| NULL | t1   |    2 | t2   |
|    1 | t1   |    3 | t2   |
|    2 | t1   |    3 | t2   |
|    3 | t1   |    3 | t2   |
| NULL | t1   |    3 | t2   |
|    1 | t1   |    4 | t2   |
|    2 | t1   |    4 | t2   |
|    3 | t1   |    4 | t2   |
| NULL | t1   |    4 | t2   |
|    1 | t1   | NULL | t2   |
|    2 | t1   | NULL | t2   |
|    3 | t1   | NULL | t2   |
| NULL | t1   | NULL | t2   |
+------+------+------+------+

Solution

  • All three expression are equivalents and will produce the same output. As mysql manual on join says:

    In MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace each other)

    ...

    INNER JOIN and , (comma) are semantically equivalent in the absence of a join condition: both produce a Cartesian product between the specified tables (that is, each and every row in the first table is joined to each and every row in the second table).