HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Outer Joins to find records with no matching associated entries

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withrecordsassociatedfindoutermatchingjoinsentries

Problem

I'm trying to find all foo records which do not have any bar records that match a given criteria.

create table foo (
  id integer
);

create table bar (
  foo_id integer,
  name varchar(255)
);

insert into foo (id) values (1),(2),(3),(4),(5),(6);
insert into bar (foo_id, name) values
 (1,"name1"),
 (2,"name1"),
 (3,"asd"),
 (4,"name2"),
 (5,"name2"),
 (3,"name1");


Based on this .. only record 6 matches the criteria since its not tagged with name1 or name2.

select
  foo.*
from foo
  left outer join bar on (foo.id = bar.foo_id)
where
  bar.name not in ("name1","name2") or bar.name is null;


What am I missing?

Solution

If you want to stick with left join, here is how it should be. The condition you want to exclude is placed on the left join .. on part and you keep the where .. is null check:

select
    foo.*
from 
    foo
  left outer join bar 
    on  foo.id = bar.foo_id
    and bar.name in ('name1', 'name2')
where 
    bar.name is null ;


It can also be done with not exists:

select
    foo.*
from 
    foo
where 
    not exists
      ( select *
        from bar 
        where foo.id = bar.foo_id
          and bar.name in ('name1', 'name2')
      ) ;

Code Snippets

select
    foo.*
from 
    foo
  left outer join bar 
    on  foo.id = bar.foo_id
    and bar.name in ('name1', 'name2')
where 
    bar.name is null ;
select
    foo.*
from 
    foo
where 
    not exists
      ( select *
        from bar 
        where foo.id = bar.foo_id
          and bar.name in ('name1', 'name2')
      ) ;

Context

StackExchange Database Administrators Q#83245, answer score: 5

Revisions (0)

No revisions yet.