Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between cross product (cross join, Cartesian product) and natural join

While writing in SQL, how would I know if I should use cross product (cross join, Cartesian product) or natural join?

like image 746
AamKhayega Avatar asked Oct 11 '14 18:10

AamKhayega


People also ask

What is difference between Cartesian product and natural join?

The cross join produces the cross product or Cartesian product of two tables whereas the natural join is based on all the columns having the same name and data types in both the tables.

What is difference between Cartesian join and cross join?

Both the joins give same result. Cross-join is SQL 99 join and Cartesian product is Oracle Proprietary join. A cross-join that does not have a 'where' clause gives the Cartesian product. Cartesian product result-set contains the number of rows in the first table, multiplied by the number of rows in second table.

Is Cartesian product and cross join same?

In SQL Server, the cartesian product is really a cross-join which returns all the rows in all the tables listed in a query: each row in the first table is paired with all the rows in the second table.


1 Answers

CROSS JOIN creates all possible pairings of rows from two tables, whether they match or not. You don't use any join condition for a cross product, because the condition would always be true for any pairing.

An example of using CROSS JOIN: you have tables of ShoeColors and ShoeSizes, and you want to know how many possible combinations there are. SELECT COUNT(*) FROM ShoeColors CROSS JOIN ShoeSizes;

NATURAL JOIN is just like an INNER JOIN, but it assumes the condition is equality and applies for all columns names that appear in both tables. I never use NATURAL JOIN, because I can't assume that just because columns have the same name, that they should be related. That would require a very strict column naming convention, and practically no real-world project has such discipline.

like image 105
Bill Karwin Avatar answered Oct 08 '22 03:10

Bill Karwin