Link to home
Create AccountLog in
Avatar of Sriv
Sriv

asked on

Conditions in Where clause

I have question. I am  Pulling my data from SQL DB and I want to exclude particular records from a table. Lets say columnA  = "A" and Status = "B" then eliminate records in columnC where ColumnC  = "A1"

How to use a if clause or case clause in where condition?
Avatar of zephyr_hex (Megan)
zephyr_hex (Megan)
Flag of United States of America image

SELECT *
FROM MyTable
WHERE (CASE WHEN columnA = 'A' AND Status = 'B' AND columnC = 'A1' THEN 0 ELSE 1 END) = 1

Open in new window


You can just specify that condition and everything else is "true", and then limit the results to just records that evaluate to "true"
Avatar of lcohan
SELECT FROM TabNAme
WHERE columnA  = 'A'
              and Status = 'B'
              and ColumnC  <> 'A1'
E.g.

SELECT T.* 
FROM schemaName.tableName T 
WHERE NOT (T.columnA = 'A' AND T.Status = 'B') AND NOT columnC = 'A1';

Open in new window

Avatar of Sriv
Sriv

ASKER

The above condition should only apply for scenario when columnA  = 'A'  and Status = 'B' not for other values
And in that case where does the "...then eliminate records in columnC where ColumnC  = "A1" stands? Is that needed or not?
If all needed is indeed "...only apply for scenario when columnA  = 'A'  and Status = 'B' " then the SELECT would be like:

SELECT FROM TabNAme
WHERE columnA  = 'A'
              and Status = 'B'
select * from table
except
select * from table
where columnA = 'A'
and Status = 'B'
and columnC = 'A1'
Avatar of Sriv

ASKER

I am using this CASE statement but it is failing
Where ColumnC <> (CASE WHEN  ColumnA ="A" AND Status = "B" THEN "A1" ELSE Nothing END)
select * from tablename
WHERE ColumnC <> (CASE WHEN  ColumnA = 'A' AND [Status] = 'B' THEN 'A1' ELSE NULL END)
ASKER CERTIFIED SOLUTION
Avatar of Sharath S
Sharath S
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer