Multiple OR’s in T-SQL WHERE Condition SQL Server

Just been rewriting some SQL Server stored procedures for a client. There were a lot of SELECT statements like the one below:

SELECT 
   *
FROM dbo.TABLE
WHERE (field1 = 'SBO' OR field1 = 'RBO' OR field1 = 'PYO' OR field1 = 'TCO'
   OR field1 = 'BRS' OR field1 = 'BMS') AND field2 = 'COMPLETED' 

I’ve seen this quite a few times, and I’m not suggesting this is wrong, however I find that this is much better written as:

SELECT 
   *
FROM dbo.TABLE
WHERE field1 IN ('SBO', 'RBO', 'PYO', 'TCO', 'BRS', 'BMS') AND field2 = 'COMPLETED' 

For me this makes it much clearer that we are comparing field1 to the the set of values and field2 to another value.

Advertisements
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s