SQL where both conditions in brackets are true

ilija veselica picture ilija veselica · Sep 17, 2015 · Viewed 8.8k times · Source
SELECT
    *
FROM 
    TableName
WHERE
    Column1 = 'X'
    AND Column2 = 'Y'
    AND (Column3 != 'D' AND Column4 != 'D') -- Want to apply this filter ONLY if both conditions are true

How to write third filter so that it's applied only if both of them are true. Currently, brackets make no difference but I need expression in brackets to be considered as a single condition

Example:

Column1     Column2     Column3     Column4
X           Y           D           L   
X           Y           L           L   
X           Y           L           D   
X           Y           D           D   -- want to remove this line

Result should be:

Column1     Column2     Column3     Column4
X           Y           D           L   
X           Y           L           L   
X           Y           L           D   

Answer

daniel picture daniel · Sep 17, 2015
SELECT
    *
FROM 
    TableName
WHERE
    Column1 = 'X'
    AND Column2 = 'Y'
    AND NOT (Column3 = 'D' AND Column4 = 'D')