Do you know that AND is much more efficient than OR in a WHERE clause?
Last updated by Bahjat Alaadel [SSW] 4 months ago.See historyTo understand why this is the case it takes a little bit of thought.
Video: Use AND instead of OR for SQL performance | Bryden Oliver (3 min)
When doing an OR, the server needs to get all the rows that match the first clause in the OR statement. Then it needs to get all the rows that match and then join the 2 results together. If you think about it this is just doing a union and you can generally write a statement with an OR using a UNION instead and the performance will improve. It will however be a bit less readable.
SELECT Id, Location, DownVotes FROM dbo.Users WHERE location = 'USA' OR DownVotes > 5;
SELECT Id, Location, DownVotes FROM dbo.Users WHERE location = 'USA'
UNION
SELECT Id, Location, DownVotes FROM dbo.Users WHERE DownVotes > 5
Now if you consider an AND, it's the same as an intersection. You can find all the rows that match the first clause, and then immediately check the row matches the second clause before adding it to the results.