Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add an AND condition to a WHERE clause in SQL Server

Tags:

sql

sql-server

I have a table with the following schema:

| ID | BUNDLE_ID | IS_ADMIN |

I need to select data from the above table having an AND clause on the basis of certain criteria, i.e

IF @FLAG = 1
    SELECT * 
    FROM TABLE A 
    WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN (3, 5)
ELSE
    SELECT * 
    FROM TABLE A 
    WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN (1, 2)

Can I achieve this in a single query?

like image 796
Paras Avatar asked Jan 23 '18 10:01

Paras


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 add condition in WHERE clause in SQL?

Yes, a CASE statement is possible in the WHERE clause but in this case it doesn't seem like you need it.

Can you have an AND in a WHERE SQL?

Yes, an SQL query can contain a WHERE and HAVING clause.

Can we use AND operator in WHERE clause?

The WHERE clause can be combined with AND , OR , and NOT operators. The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE.


1 Answers

General approach is to rewrite the query with a boolean expression that evaluates to what you need based on flag's value:

SELECT * FROM TABLE A WHERE A.IS_ADMIN = 1 AND ( -- Common part ...
    (@Flag=1  AND BUNDLE_ID IN(3,5))     -- IF   ...
OR
    (@Flag<>1 AND BUNDLE_ID IN(1,2))     -- ELSE ...
)
like image 74
Sergey Kalinichenko Avatar answered Nov 15 '22 08:11

Sergey Kalinichenko