by ericHosick · 5y ago · 0 comments
I think a cartesian product would be:
SELECT * FROM A, B; Given sizes a, b the resulting number of rows would be a X b or O(N^2).
With a join SELECT * FROM A INNER JOIN B ON A.id = B.id then the result rows would be MAX(a,b) or O(N).
A JOIN is a predicate that filters down the dataset.
select * from A, B /* this is cartesian that slows down your query */ WHERE a.col1=B.col2
in fact both queries produce the same execution plan if you check yourself
select * from customer_order_items
the grain is one row per customer order item, and the next two joins don't change that select * from customer_order_items join customer_orders on order_id
the grain is still one row per customer order item select * from customer_order_items join customer_orders on order_id join customers on customer_id
the grain is still one row per customer order item..etc..
of course later on they screw it up and take the cartesian product of customer_order_items by employ_markouts, but it's just 2 big factors not 7 - their query did finish after a few seconds. usually mistakes involving cartesian products with 7 factors just run for hours and eventually throw out of memory.
my explanation to this: CPUs ave very fast. My CPU is 4Ghz so a single core can do a lot of computations in one second, and a SQL engine is smart enough to make cartesian computation (as part of a query plan) and discard the result if row does not meet predicate condition.
in fact I agree that not entire cartesian is being computed, if you specify enough predicates. But the query still multiplies rows. In the author's article he is joining employees when customer_id columns in NULL so this is technically a cartesian, because NULL predicate is not very selective (=there are a lot of rows with value of NULL)
(Note when I say linear performance, I mean the join predicate is executed a linear amount of times, but the initial sort/hash operation was probably more like O(n log n))