I want to know if the SQL Server query optimizer is ever smart enough to look inside a CASE
expression when it figures out execution plans.
For purposes of reporting, I have written a view
that encapsulates logic for classifying records. It adds a "status" column based on a number of lookups elsewhere in the database. Here's a simple example:
create view LibraryBook_with_Status
as
select
LibraryBook.*,
case
when (some logic) then 'Deleted'
when (more logic) then 'Checked Out'
when (more logic) then 'Out for Repair'
when (more logic) then 'On Hold'
else 'On the Shelf'
end as [Status]
from
LibraryBook
left outer join
(bunch of other tables used in Status calculation, preserving cardinality)
I would like to use this view
in other queries and have SQL Server create execution plans that takes the CASE
logic into account. For example:
select *
from LibraryBook_with_Status
where [Status] = 'Deleted'
If this query was written referencing only base tables instead of the view
, it would only use LibraryBook
and those tables in the first clause of the CASE
expression. But, based on my rudimentary tests, SQL Server seems to be calculating the status of all rows and then filtering. This is much more inefficient.
If the CASE
expression really is a black box, then I see a trade-off between maintainability and query execution speed.
So, is it not possible to encapsulate logic like this without compromise? Is there some way of formulating a view
that enables more efficient query plans to be built?