Find records with no associated records using outer joins

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2022-12-01

Say you have the following schema

- id
- email

- id
- name
- user_id

i.e. a User has many Products.

This might be modelled in Rails etc. with:

class User
  has_many :products

class Product
  belongs_to :user

Given that, how would you get the users that have zero products?

The trick is to use an outer join and then a where clause looking for when the user_id is null.

So something like this:

FROM users 
LEFT OUTER JOIN products ON products.user_id = 
WHERE user_id is null;

Would an inner join on user_id work? No because this filters any users that have no products.