質問

Following is my query which I want to optimize, here the bottleneck for the optimization is CONDITION_B.

select @COMPUTE_X = count(distinct TABLEA.COLUMN_T5)
from #TMP_TABLEA TABLEA
inner join TABLEB on TABLEB.ID = TABLEA.ID
left join....
where
(
  CONDITION_A --Complex condition
) and
(
  CONDITION_B --Complex condition with some functions returning table
)

If I put my result of above query leaving CONDITION_B to a temporary table and then apply CONDITION_B on that temporary table, I achieve a very good amount of performance gain. I think CONDITION_B always evaluated whether the result for CONDITION_A is false.

Could anyone let me know if there is a better way of doing it. And does short-circuit operations work in SQL query statement, if yes what is the order of their processing.

役に立ちましたか?

解決

The only way to enforce the order of evaluation is to use the CASE statement. Although it might not look pretty, the following might have similar performance:

select @COMPUTE_X = count(distinct TABLEA.COLUMN_T5)
from #TMP_TABLEA TABLEA
inner join TABLEB on TABLEB.ID = TABLEA.ID
left join....
where 1 = (CASE WHEN CONDITION_A then 1
                WHEN CONDITION_B then 1
                else 0
           end)

Remember, SQL is a descriptive language not a procedural language. You write the SQL to describe the results that you want. The order that you place things in a statement can be totally rearranged by the query optimizer. However, CASE statements are one exception. The order of evaluation is guaranteed in most cases (although not when aggregations are involved).

By the way, if you post another query with the full query, there may be other opportunities to speed the query.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top