1

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.

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

2 Comments

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
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.
0

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 :)

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.