Sql Server predicates lazy?

后端 未结 4 1882
南旧
南旧 2021-01-17 21:01

I have a query:

SELECT 
    someFields 
FROM 
    someTable 
WHERE 
    cheapLookup=1 
    AND (CAST(someField as FLOAT)/otherField)<0.9

4条回答
  •  生来不讨喜
    2021-01-17 21:25

    SQL is declarative: you tell the database what you want, not how you want it done. The database is entirely free to evaluate lazily or eagerly. In fact, it can evaluate thrice in reverse order for all I know :)

    In rare cases, you can improve performance by reframing your query in such a way that it avoids a specific expensive operation. For example, moving the floating point math to a separate query would force lazy evaluation:

    declare @t table (id int, someField float, otherField float)
    insert @t select id, someField, otherField from someTable 
        where cheaplLookup <> 1
    delete @t where (CAST(someField as FLOAT)/otherField) >= 0.9
    insert @t select id, someField, otherField from someTable 
        where cheaplLookup = 1
    

    In your example, I would expect SQL Server to choose the best way without any hints or tricks.

提交回复
热议问题