SQL-IF statement around AND

I am trying to create a query that will only add AND clauses where certain conditions are met.

This is what I need:

SELECT DISTINCT id name active FROM team WHERE id = 1234 IF team.active = 'y' AND team.id IN { query } ELSEIF team.active = 'n' AND team.id IN { query } 

But I'm not sure how to do this in SQL. Any suggestions?

+4
source share
3 answers
  SELECT DISTINCT id name active FROM team WHERE id = 1234 AND (team.active = 'y' AND team.id IN { query }) OR (team.active = 'n' AND team.id IN { query }) 

You use the AND and OR logic to create the logic.

+5
source

You can use logical logic like this

 SELECT ... FROM team WHERE id = 1234 AND ( (team.active = 'y' AND team.id IN query) OR (team.active = 'n' AND team.id IN query) ) 

Did I miss the difference in the two branches?

+3
source

You can use the decoding instruction to achieve the result.

 SELECT DISTINCT id name active FROM team WHERE id = 1234 and team.id in ( decode (team.active,'y',(query),'n',(query)) 

you can also use case argument

-1
source

All Articles