1

I'd like to know if it would be possible to get the following behavior with one query only.

Filter the results with WHERE but only apply the filter if the result isn't empty, like an optional WHERE.

For instance considering there is an users table and I want to retrieve all the users from Spain, but if there aren't any then I want all users (like the Where wouldn't be applied).

Instead of:

SELECT * FROM users WHERE country = sp

If result empty then

SELECT * FROM users

I wanted to do this behavior in one sql statement...is it possible?

1 Answer 1

2
select *
from users
where
    country = sp
    or not exists (select 1 from users where country = sp)
Sign up to request clarification or add additional context in comments.

1 Comment

pretty elegant. i like that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.