Skip to content
Advertisement

How to create right query?

I’m trying write a query:

SELECT id FROM users WHERE status = 3

But if this sample returns an empty response, then I need instead to select the id where status = 4, and if it returns empty again, where status = 5.

How can I write a single query to solve this?

Advertisement

Answer

I will use the case statement in the where clause:

select id 
from users
where status = case when status = 3 and id is null then 4
                    when status = 4 and id is null then 5
               else 3
               end

Let me know if you have any question.

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