Utilizando "exception join" em SQL
Um exception join retorna apenas os registros da primeira tabela que não possuem um registro correspondente (de acordo com a condição) na segunda tabela.
A sintaxe do “exception join” do SQL é difícil de ser entendida e raramente é utilizada. Nesta dica veremos como trabalhar com este comando SQL através dois exemplos.
Considere as duas tabelas seguintes:
> select * from employee
EMPLOYEEID EMPLOYEENAME DEPARTMENTID
1 Greg Graffin 1
2 Dino Cazares 2
3 Burton Bell 2
4 Lee Ving 4
5 Mike Levine 4
6 Devin Townsend 6
7 Otep Shamaya 7
> select * from department
DEPARTMENTID DEPARTMENTNAME
1 HR
2 IS
3 QA
4 CR
Para encontrar os empregados com um departamento inválido faça:
> select
Employee.employeeName
from
Employee
exception join
Department
on
Employee.departmentID = Department.departmentID
EMPLOYEENAME
Devin Townsend
Otep Shamaya
Para encontrar os departamentos que não contêm empregados, faça:
> select
Department.departmentName,
Department.departmentID
from
Department
exception join
Employee
on
Employee.departmentID = Department.departmentID
DEPARTMENTNAME DEPARTMENTID
QA 3
O comando exception join é funcionalmente equivalente a:
SELECT
Employee.employeeName
FROM
Employee
where
not exists
(select * from Department
where Employee.departmentID = Department.departmentID)
ou
> select
Employee.employeeName
from
Employee
where
Employee.departmentID not in
(select departmentID from Department)