rethabile
rethabile

Reputation: 3197

SQL query where based on column value

Is there an SQL query that change condition based on value of other column?

I want to perform a query that does the following

select colA,colB, colC
from TABLED
where colA > 10
  and (if colC == A then colB = 'C' else colB = 'B')

If that even makes sense, if colC == A we would have

select colA, colB, colC
from TABLED
where colA > 10 and colB = 'C'

otherwise we would have

select colA,colB,colC
from TABLED
where colA > 10 and colB = 'B'

Upvotes: 2

Views: 1347

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271151

You can express this using conditional logic. No case is required:

select colA, colB, colC
from TABLED
where colA > 10 and
      ( (colC = A and colB = 'C') or
        (colC <> A and colB = 'B')
      );

This does not take into account that colC might be NULL. That is easy to incorporate into the query, if it needs to.

Upvotes: 2

Related Questions