简体   繁体   中英

How does Oracle execute queries

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 ?

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM