Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason this simple SQL query should be so slow?

Tags:

sql

This query takes about a minute to give results:

SELECT MAX(d.docket_id), MAX(cus.docket_id) FROM docket d, Cashup_Sessions cus

Yet this one:

SELECT MAX(d.docket_id) FROM docket d UNION MAX(cus.docket_id) FROM Cashup_Sessions cus

gives its results instantly. I can't see what the first one is doing that would take so much longer - I mean they both simply check the same two lists of numbers for the greatest one and return them. What else could it be doing that I can't see?

I'm using jet SQL on an MS Access database via Java.

like image 265
Jack Avatar asked Jul 06 '10 12:07

Jack


2 Answers

the first one is doing a cross join between 2 tables while the second one is not.
that's all there is to it.

like image 107
Mladen Prajdic Avatar answered Oct 27 '22 01:10

Mladen Prajdic


The first one uses Cartesian product to form a source data, which means that every row from the first table is paired with each row from the second one. After that, it searches the source to find out the max values from the columns.

The second doesn't join tables. It just find max from the fist table and the max one from the second table and than returns two rows.

like image 25
Nenad Dobrilovic Avatar answered Oct 27 '22 01:10

Nenad Dobrilovic