Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL not equal operator vs Case statement

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.

like image 974
Mikaere Avatar asked Feb 04 '26 13:02

Mikaere


1 Answers

You have to be more specific at what information you are interested in the table and what are the possible values of the Code column. Then you can create appropriate indexes to speed up the query.

For example, if values in the Code column could only be one of 'RandomCode', 'OtherCode', 'YetAnotherCode', you can re-write the query as:

SELECT * FROM MyTable WHERE Code = 'OtherCode' OR Code = 'YetAnotherCode'

And of course you need an index on the Code column.

If you have to do an inequality query, you can change SELECT * to a more narrow query like:

SELECT Id, Name, Whatever FROM MyTable WHERE Code != 'RandomCode'

Then create an index like:

CREATE INDEX idx_Code ON MyTable(Code) INCLUDE (Id,Name,Whatever)

This can reduce I/O by replacing a table scan with an index scan.

like image 108
Todd Li Avatar answered Feb 06 '26 01:02

Todd Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!