patternMinor
EXISTS clause in SQL
Viewed 0 times
sqlclauseexists
Problem
I have following requirement:
I want result of ids that exist in user_input table. If nothing in user_input table then I want all the ids from main_input table.
Here's what I have so far:
main_set table has all the ids, user_input table has all user entered ids.I want result of ids that exist in user_input table. If nothing in user_input table then I want all the ids from main_input table.
Here's what I have so far:
create table main_set as
select 1 id from dual
union all
select 2 from dual
union all
select 3 from dual
create table user_input as
select 1 id from dual
union all
select 2 from dual
select *
from main_set ms
where exists (select null
from user_input ui
where ui.id = ms.id)Solution
select id from user_input
union all
select id from main_set where not exists(select * from user_input);--edit based on your comment
select *
from main_set
where id in(select id from user_input) or not exists(select * from user_input)or, seeing as you mention performance, perhaps you should try a join as an alternative:
select main_set.*
from main_set left outer join user_input on(user_input.id=main_set.id)
where user_input.id is not null or not exists(select * from user_input)Code Snippets
select id from user_input
union all
select id from main_set where not exists(select * from user_input);select *
from main_set
where id in(select id from user_input) or not exists(select * from user_input)select main_set.*
from main_set left outer join user_input on(user_input.id=main_set.id)
where user_input.id is not null or not exists(select * from user_input)Context
StackExchange Database Administrators Q#4900, answer score: 3
Revisions (0)
No revisions yet.