Home > database >  SQL - Exclude rows from SELECT statement if a certain column combination exists in that row
SQL - Exclude rows from SELECT statement if a certain column combination exists in that row

Time:04-12

I have an SQL select statement with many columns. However I want to exclude an entire row if certain column combinations exist.

My query looks something like this:

SELECT COLUMN1, COLUMN2, COLUMN3
FROM TABLE
WHERE NOT (COLUMN2 = 'A' AND COLUMN3 = 'B')
AND NOT (COLUMN2= 'B' AND COLUMN3 = 'C')
.
.
.

This doesn't seem to work, I am getting a "missing expression" error. What is the correct way to exclude entire rows when column combinations match certain conditions?

Thank you!

CodePudding user response:

Since a row can only match one of those conditions at one time, you should be using OR:

SELECT COLUMN1, COLUMN2, COLUMN3
FROM YourTable
WHERE NOT (    
    ( COLUMN2 = 'A' AND COLUMN3 = 'B' )
     OR 
    ( COLUMN2= 'B' AND COLUMN3 = 'C' )
)

db<>fiddle here

  •  Tags:  
  • sql
  • Related