Skip to content
Advertisement

How to filter out a column value when another column contains a value in SQl

How can I filter out a value in one column if a value in another column is present? I’m trying to remove all C’s in the CODE column if it is accompanied by a ‘-‘ in the Description column.

CODE |  Description
A      -
A      -
B      -
B      -
C      stuff
C      -

In the ‘CODE’ column, I want to remove the values ‘C’ if the Description = ‘-‘.

The end result would look like the table below with the C & – removed.

CODE |  Description
A      -
A      -
B      -
B      -
C      stuff

Of note, the Description column is a custom field using CASE WHEN.

In excel, I would just create a dummy conditional column and then filter ‘C’ &’-‘ out. I’m not sure how to go about doing this in SQL.

Advertisement

Answer

One way to express this uses not:

where not (code = 'C' and Description = '-')

This seems quite close to the logic as your express it.

This is equivalent to:

where code <> 'C' or Description <> '-')

Note that both these solutions assume that code and description are not NULL. They can be modified to handle that as well, but that does not seem necessary based on the data in the question.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement