I can create the following constraint on the AdventureWorks table Person.Person:
ALTER TABLE Person.Person ADD CONSTRAINT ConstantScan CHECK (LastName <> N'Doesn''t Exist')
This tells SQL Server that no LastName can have the value of Doesn't Exist
The Optimizer uses this to its advantage in the following simple query:
SELECT *
FROM Person.Person
WHERE LastName = N'Doesn''t Exist'
As the constraint tells the optimizer that nothing in the column can equal the value we are equality searching for (assuming a trusted constraint), the optimizer just performs a constant scan and does "nothing"
If I drop the constraint above and create a slightly different one:
ALTER TABLE Person.Person ADD CONSTRAINT ConstantScan2 CHECK (LastName <> N'Doesn''t Exist' AND FirstName <> N'Doesn''t Exist')
and run a query with a predicate who's results would violate the check constraint:
SELECT *
FROM Person.Person
WHERE FirstName = N'Doesn''t Exist' AND
LastName = N'Doesn''t Exist'
We get an index seek with a Key Lookup
However, If I run
SELECT *
FROM Person.Person
WHERE FirstName = N'Doesn''t Exist' AND
LastName = N'Doesn''t Exist'
with just the original constraint in place:
ALTER TABLE Person.Person ADD CONSTRAINT ConstantScan CHECK (LastName <> N'Doesn''t Exist')
Again, I get the constant scan
Why can we not get a constant scan when running the query with two predicates when the constraint prohibits its results? Am I right in assuming this is just a limitation of the functionality within the optimizer?