Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL where field in vs. where field = with multiple ors?

Tags:

syntax

sql

Which of these is better to use in regard to performance? ...in regard to readability / understandability? ...in regard to accepted standards?

SELECT *
FROM Wherever
WHERE Greeting IN ('hello', 'hi', 'hey')

OR

SELECT *
FROM Wherever
WHERE Greeting = 'hello' 
   OR Greeting = 'hi'
   OR Greeting = 'hey'

The first seems more intuitive / clear to me, but I'm unsure of accepted standards and performance.

like image 726
froadie Avatar asked Feb 26 '10 16:02

froadie


People also ask

Can we use multiple conditions in WHERE clause in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.

Can we use multiple columns in WHERE clause?

If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.

Can we use two columns in WHERE clause in SQL?

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.

Can we use WHERE AND group by together in SQL?

GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause. In the query, GROUP BY clause is placed before ORDER BY clause if used any.


1 Answers

It more readable, and more universally accepted to do:

SELECT *
FROM Wherever
WHERE Greeting in ('hello', 'hi', 'hey')

All modern SQL servers optimize your queries, so they're both likely to be changed into the same code that runs on the server, so performance differences will be negligible or non-existent.

Edit:

Apparently the in option is faster, as it evaluates to a binary lookup, whereas the multiple = just evaulates each statement individually.

like image 86
Mike Trpcic Avatar answered Sep 30 '22 05:09

Mike Trpcic