Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL where both conditions in brackets are true

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   
like image 655
ilija veselica Avatar asked Sep 17 '15 10:09

ilija veselica


2 Answers

SELECT
    *
FROM 
    TableName
WHERE
    Column1 = 'X'
    AND Column2 = 'Y'
    AND NOT (Column3 = 'D' AND Column4 = 'D')
like image 164
daniel Avatar answered Oct 24 '22 12:10

daniel


You need an OR:

SELECT
    *
FROM 
    TableName
WHERE 
    (Column1 <> 'X' OR Column2 <> 'Y')
OR
    (Column1 = 'X' AND Column2 = 'Y' AND (Column3 != 'D' AND Column4 != 'D')) 

Side-note: your expected result is wrong or your codition. This is the result with your coditions. I guess you want Column3 != 'D' OR Column4 != 'D' instead of Column3 != 'D' AND Column4 != 'D'.

Then this is more appropriate and returns your expected result:

SELECT
    *
FROM 
    TableName
WHERE 
    (Column1 <> 'X' OR Column2 <> 'Y')
OR
    (Column1 = 'X' AND Column2 = 'Y' AND (Column3 != 'D' OR Column4 != 'D')) 

Demo

like image 36
Tim Schmelter Avatar answered Oct 24 '22 13:10

Tim Schmelter