Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE clause with nested multiple conditions

I want to retrieve data with conditions in WHERE clause.
Here is my table something look like:

Name   Location    Age
----------------------
AAA     Bhuj       24
BBB     Mumbai     22
CCC     Bhuj       18
DDD     Bhuj       27
EEE     Mumbai     26

My condition in WHERE clause is:
if location = 'Bhuj' then Age>20 else if location = 'Mumbai' then Age>25

I am trying this code to achieve this:

SELECT * FROM testing
WHERE 
CASE Location WHEN 'Bhuj' THEN Age>20
              WHEN 'Mumbai' THEN Age>25
END;

This code works fine for MySQL (see this SQLFiddle) but does not work for SQL Server (see this SQLFiddle) and giving the following error:

Incorrect syntax near '>'.: SELECT * FROM testing WHERE case Location When 'Bhuj' then Age>20 When 'Mumbai' then Age>25 end

Any suggestion?

like image 671
Himanshu Jansari Avatar asked Aug 30 '12 07:08

Himanshu Jansari


People also ask

Can we use 2 conditions in WHERE clause?

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.

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.

WHERE is nested condition?

Nested conditions comprise condition statements contained within the definition of other condition statements. Nested conditions work as follows: You can group multiple condition statements. Conditions consisting of multiple statements are connected using the logical AND and OR operators.


1 Answers

I think this is what you're trying to achieve

   SELECT * 
   FROM testing
   WHERE (Location = 'Bhuj' AND Age>20) 
        OR (Location = 'Mumbai' AND Age>25)

Check SQLFiddle

UPDATE:

Case statement returns a value, you can't have a condition inside it.

like image 87
hgulyan Avatar answered Oct 07 '22 04:10

hgulyan