Assume I have a T-SQL statement:
select * from MyTable
where Code != 'RandomCode'
I’ve been tasked with making this kind of where statement perform more quickly. Books Online says that positive queries (=) are faster than negative (!= , <>).
So, one option is make this into a CASE statement e.g.
select * from MyTable
where
case when Code = 'RandomCode' then 0
else 1 end = 1
Does anyone know if this can be expected to be faster or slower than the original T-SQL ?
Thanks in advance.
You have to be more specific at what information you are interested in the table and what are the possible values of the
Codecolumn. Then you can create appropriate indexes to speed up the query.For example, if values in the
Codecolumn could only be one of'RandomCode','OtherCode','YetAnotherCode', you can re-write the query as:And of course you need an index on the
Codecolumn.If you have to do an inequality query, you can change
SELECT *to a more narrow query like:Then create an index like:
This can reduce I/O by replacing a table scan with an index scan.