An interesting question would involve relational division, or how to express a "for all" relationship, which would require nested not exists
clauses.
The question comes straigh from this link.
Given the following tables, representing pilots that can fly planes and planes in a hangar:
create table PilotSkills (
pilot_name char(15) not null,
plane_name char(15) not null
)
create table Hangar (
plane_name char(15) not null
)
Select the names of the pilots who can fly every plane in the hangar.
The answer:
select distinct pilot_name
from PilotSkills as ps1
where not exists (
select * from hangar
where not exists (
select * from PilotSkills as ps2 where
ps1.pilot_name = ps2.pilot_name and
ps2.plane_name = hangar.plane_name
)
)
Or ...
Select all stack overflow users that have accepted answers in questions tagged with the 10 most popular programming languages.
The (possible) answer (assuming an Accepted_Answers
view and a Target_Language_Tags
table with the desired tags):
select distinct u.user_name
from Users as u
join Accepted_Answers as a1 on u.user_id = a1.user_id
where not exists (
select * from Target_Language_Tags t
where not exists (
select *
from Accepted_Answers as a2
join Questions as q on a2.question_id = q.question_id
join Question_Tags as qt on qt.question_id = q.question_id
where
qt.tag_name = t.tag_name and
a1.user_id = a2.user_id
)
)