Skip to content
Advertisement

Very slow query when using CONNECT BY LEVEL

NEEDS

I want to create a table like the following in Oracle SQL:

Every warehouse in WMWHSE_ID will be printed with a DATE column for today’s date, and this will be repeated for DATE = yesterday, the day before yesterday, the day before that…etc until exactly 1 week ago. I have 124 warehouses total, so 124*7 = 868 rows total.

===

QUERY BLOCK

The following is my query. It uses the CONNECT BY LEVEL <= to achieve the 7 dates (in theory)

(The GROUP BY is needed, because without it the table looks like:)

===

THE ISSUE

The query time seems to grow exponentially with n in CONNECT BY LEVEL <= n. I ran some testing and got the following:

Anything n=4 and up seems to just hang sqldeveloper completely. When n=7, I left the computer running for 30+ minutes and the query was still running.

What is causing this slowness? Is there a better way to go about implementing my table? Thanks for your time.

Advertisement

Answer

Why is query so slow? Because each iteration connects each row with 124 new rows. So at second level it is 124 * 124 rows, at fourth level you get 236421376 rows, at seventh level 450766669594624 rows. This is why you get duplicates. Also join with dual has no impact.

The solution is to correct connect by part, add condition wmwhse_id = prior wmwhse_id:

It is even easier with recursive CTE, which is standard in most databases:

But simplest is to make cross join with 7 numbers, doesn’t matter how you generate them:

dbfiddle containing all three queries.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement