Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select ..... where .... OR

Tags:

mysql

Is there a way to select data where any one of multiple conditions occur on the same field?

Example: I would typically write a statement such as:

select * from TABLE where field = 1 or field = 2 or field = 3

Is there a way to instead say something like:

select * from TABLE where field = 1 || 2 || 3

Any help is appreciated.

like image 849
jessilfp Avatar asked Aug 20 '08 12:08

jessilfp


People also ask

Can we use SELECT in WHERE clause?

The WHERE clause can be used with SQL statements like INSERT, UPDATE, SELECT, and DELETE to filter records and perform various operations on the data. We looked at how to query data from a database using the SELECT statement in the previous tutorial.

Can I use two and 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.

Should I use WHERE or join?

Actually you often need both "WHERE" and "JOIN". "JOIN" is used to retrieve data from two tables - based ON the values of a common column. If you then want to further filter this result, use the WHERE clause. For example, "LEFT JOIN" retrieves ALL rows from the left table, plus the matching rows from the right table.

Can I use or in WHERE SQL?

The OR condition can be used in the SQL UPDATE statement to test for multiple conditions. This example would update all favorite_website values in the customers table to techonthenet.com where the customer_id is 5000 or the last_name is Reynolds or the first_name is Paige.


2 Answers

Sure thing, the simplest way is this:

select foo from bar where baz in (1,2,3)
like image 122
mercutio Avatar answered Oct 07 '22 17:10

mercutio


select * from TABLE where field IN (1,2,3)

You can also conveniently combine this with a subquery that only returns one field:

    select * from TABLE where field IN (SELECT boom FROM anotherTable)
like image 38
Michael Stum Avatar answered Oct 07 '22 15:10

Michael Stum