简体   繁体   English

Oracle如何执行查询

[英]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 . 我这样做是为了避免选择全部然后进行过滤,但是我不确定Oracle将如何处理它,通常在y IN ('a','b')返回false时,Oracle不应该执行sq1

So does any one know how Oracle will execute this ? 那么,有人知道Oracle将如何执行此操作吗?

Oracle will execute it according to the execution plan . Oracle将根据执行计划执行它。 The execution plan is prepared by the SQL optimizer (as one of the initial phases of the execution), according to: SQL优化器 (作为执行的初始阶段之一)根据以下条件来制定执行计划:

  • The real data and statistics of each table, 每个表的真实数据和统计信息,
  • The existing indexes on the tables. 表上的现有索引
  • The selectivity of the filters (WHERE conditions). 过滤器的选择性 (WHERE条件)。
  • Available algorithms to choose from. 可供选择的算法
  • Hints that you may add to the SQL in the form of comments. 您可以以注释形式添加到SQL的提示
  • Many other variables. 许多其他变量。

To find out how Oracle will execute your specific query, run: 要了解Oracle将如何执行您的特定查询,请运行:

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). 请记住,执行计划会根据表中的实际数据及时更改,因为Oracle可能会发现一段时间后以其他方式进行操作会更便宜(有时可能会出错)。

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. 如果表从1000行增加到100万行,那么今天的计划可能与明天看到的计划不同。 It's adapts to the reality, as long as you keep the statistics updated. 只要您更新统计信息,它就会适应现实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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