0

Let's say I have a query like this :

SELECT *
FROM
  (SELECT x,y,z
   FROM Foo
   WHERE x NOT IN (sq1)
   UNION SELECT x,y,z
   FROM Foo2
   WHERE x NOT IN (sq2))
WHERE y IN ('a','b')
  AND z IN ('xa','xb','xc')

And then I transform it to this:

SELECT x,y,z
   FROM Foo
   WHERE x NOT IN (sq1) AND y IN ('a','b') AND z IN ('xa','xb','xc')
UNION 
SELECT x,y,z
   FROM Foo2
   WHERE x NOT IN (sq2) AND y IN ('a','b') AND z IN ('xa','xb','xc')

I did this to avoid selecting all and then filtering, but I'm not sure about how Oracle will treat this, normally when y IN ('a','b') is returning false Oracle shouldn't execute the sq1.

So does any one know how Oracle will execute this ?

Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • 3
    Watch the execution plan – Ludovic Feltz Apr 12 '18 at 14:26
  • 2
    Possible duplicate of [how can i see the execution plan](https://stackoverflow.com/questions/11799344/how-can-i-see-the-execution-plan) – Mike G Apr 12 '18 at 14:27
  • 1
    What are `sq1` and `sq2`? They look like a column names. – Gordon Linoff Apr 12 '18 at 14:27
  • 2
    Don't make assumptions about how your database is going to execute your sql. Look at the execution plan and see how it will actually execute your sql. You may be surprised that your assumptions are wrong and that there is a lot more complexity under the hood. – JNevill Apr 12 '18 at 14:29

1 Answers1

1

Oracle will execute it according to the execution plan. The execution plan is prepared by the SQL optimizer (as one of the initial phases of the execution), according to:

  • The real data and statistics of each table,
  • The existing indexes on the tables.
  • The selectivity of the filters (WHERE conditions).
  • Available algorithms to choose from.
  • Hints that you may add to the SQL in the form of comments.
  • Many other variables.

To find out how Oracle will execute your specific query, run:

explain plan for <my-query>

Then look at the plan using:

select plan_table_output 
  from table(dbms_xplan.display('plan_table',null,'typical'));

This will give you the details you are looking for. Of course you'll need to learn how to read the plan. It's not difficult but it will take you a few weeks of study. A hint: a plan takes the form of a tree where leaf nodes are executed first, until you execute the root node at the end.

Please keep in mind that the execution plan will change in time according to the real data in the tables, since Oracle may find it's cheaper to do it in a different way after some time (it can be wrong sometimes).

The plan you have today may be different than the one you see tomorrow, if your tables grow from 1000 rows to one million rows. It's adapts to the reality, as long as you keep the statistics updated.

The Impaler
  • 45,731
  • 9
  • 39
  • 76