简体   繁体   中英

Change SQL query to explicitly control the execution sequence

Say I have a query:

SELECT * FROM tb1
WHERE col1 = 1
 AND col2 = 2

Assume col1 is more selective and the engine will normally execute col1 = 1 firstly to gain better performance. If the conditions become more complicated, the engine may easy to make the wrong decision. So I want to control the execution sequence explicitly, how can I make it?

I guess one way may work. Firstly query

SELECT * FROM tb1
WHERE col1 = 1

select the result into a temp table, then filter by col2 = 2 , but as the conditions grow more and more, of course it's impossible to create so many temp table. Any ideas?

Update 1

People say the optimizer always makes the right decision on which filter should be executed firstly to gain better performance, but I still suspect it can work 100% of the time as the query grows larger and more complicated.

Another question, can I change the execution order by subquery or CTE? like:

SELECT * FROM 
(
   SELECT * FROM tb1 WHERE col1 = 1
)t
WHERE col2 = 2

Usually SQL Optimizer can find the better plan, but if you want to fix it, there are options...

You may create a test data set for which SQL engine chooses correct (desired) plan, then you can extract the query plan to XML string (see SET SHOWPLAN_XML ON ) and finally use WITH PLAN option (query hint) to fix the plan.

Keep in mind that query will fail if you change the schema in the future without updating the plan.

To achieve this you should use query hints.

  1. You can use USE PLAN query hint.
  2. Use with(index(index_name)) created for specific row order.

For the first point you have to get XML plan by first executing your query in which you are getting your desired execution order. And for second one, just create index on those columns in which you have arranged column in desired order.

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