Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Where Clause with multiple values

Tags:

sql

mysql

I have a query say SELECT name,number FROM TABLE WHERE number='123'
What I want is to display multiple records using where clause or any other way so that I can get following data.

Name Number ABC 123 PQR 127 PQR 130

I tried using AND && , in where clause.i.e. where number=123,127,130 or where number=123 AND 127 AND 130etc. but nothing works.

like image 976
vishalkin Avatar asked Jun 26 '14 06:06

vishalkin


People also ask

Can we use multiple values in WHERE clause in SQL?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

Can we use multiple AND in WHERE clause?

You can use the AND condition in the WHERE clause to specify more than 1 condition that must be met for the record to be selected. Let's explore how to do this. This example uses the WHERE clause to define multiple conditions.

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.

What is like %% in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.


2 Answers

just use an IN clause

where number in (123, 127, 130)

you could also use OR (just for info, I wouldn't use this in that case)

where number = 123 or
      number = 127 or
      number = 130

Don't forget round braces around the "ors" if you have other conditions in your where clause.

like image 97
Raphaël Althaus Avatar answered Sep 24 '22 06:09

Raphaël Althaus


Try this

SELECT name,number FROM TABLE WHERE number IN (123,127,130);

OR

SELECT name,number FROM TABLE
                   WHERE number = 123
                   OR number = 127
                   OR number = 130;
like image 33
Sadikhasan Avatar answered Sep 24 '22 06:09

Sadikhasan