views:

35

answers:

2

I have to tables as follows;

  1. Employees: Name nvarchar(50), Job Title nvarchar(50) and Salary int.
  2. Employers: Name nvarchar(50), Job Title nvarchar(50)

I would like to select every item from the 'Employers' table where 'Job Title' does NOT show up in the 'Employees' table.

I know this is a simple query but it has me stumped. I'd be grateful for any help. Thanks.

+1  A: 
select * from employers 
where jobtitle not in (select jobtitle 
     from employees
     where jobtitle is not null);

I would consider having a jobs table with foreign keys to both employees and employers

edit - thanks all for the not null fix

itchi
If any employee has a `null` job title, this query will return zero rows. `x not in (null, 'a', ...` -> `x <> null and x <> 'a' and ..` evaluates to unknown
Andomar
Wow, just tested that cos I'd never encountered it and it's true. Fixed by adding `where jobtitle is not null` to the subselect, though.
Blorgbeard
A: 

You could use a join:

select * 
from employers 
left join (
    select distinct jobtile
    from employees
) emp on employers.jobtitle = emp.jobtitle
where emp.jobtitle is null

Itchi's approach is more readable, but don't forget an where jobtitle is not null at the end of the subquery :)

Andomar
this will not return the desired output unless there is a employers.jobtitle = null. forgot a left join somewhere?
Chris Bednarski
Thanks for the help.
Bram
Don't do this on SQL server, it's not smart enough to understand it is an anti-join.
erikkallen