0

I have two tables, People, and Vehicles. Vehicles belongs to people. Im trying to check if a person does not have a vehicle. I was attempting to do this by joining People and Vehicles, and displaying the persons ID that is NOT IN Vehicles.person_id.

This is returning nothing, and has me wondering if there is something I did wrong, or if there is a more efficient way of doing this.

Query is below

Select People.id From People INNER JOIN Vehicles on People.id=Vehicles.person_id where People.id NOT IN Vehicles.person_id;

4 Answers 4

2

Use left join to figure out the persons with no vehicles

  Select distinct People.id 
  From People 
  LEFT JOIN Vehicles on        People.id=Vehicles.person_id 
  where Vehicles.person_id is NULL
Sign up to request clarification or add additional context in comments.

2 Comments

You may want a SELECT DISTINCT here if one person is allowed to have many vehicles.
this executes much faster than where not in
2

NOT IN can have issues with NULL values, and should probably be avoided for performance reasons if the subquery is very large.

Try NOT EXISTS:

SELECT p.id
FROM People p
WHERE NOT EXISTS (
    SELECT 1 
    FROM Vehicles v
    WHERE v.person_id = p.id)

Comments

1

another solution, using sets:

Select id From People
except
SELECT person_id FROM Vehicles

Comments

0

Use Subquery as below:

Select id 
From People
WHERE id NOT IN (SELECT distinct person_id
                 FROM Vehicles 
                 WHERE  person_id IS NOT NULL)

select all people who are not in (by Select id From People WHERE id NOT IN) the List of all the people who has vehicle by SELECT distinct person_id FROM Vehicles (you could avoid null as well here if you want).

2 Comments

ahh, nice. This doesnt return anything though. Any suggestions?
@ColtonSeal: you most probably have null values in the person_id column. Use select person_id from vehicles where person_id is not null) in the sub-select (the distinct is useless)

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.