Video in progress
You can write one task with either a subquery or a JOIN. How do you choose?
If you need columns from the other table in the result, use a JOIN. If you only need a "does it exist or not" check, an EXISTS subquery is clearer and doesn't produce duplicates. In many cases PostgreSQL turns both into the same plan, so choose by readability first.
📖 Answer
The task: users who have at least one order.
-- JOIN: a user is repeated once per order
SELECT DISTINCT u.* FROM users u JOIN orders o ON o.user_id = u.id;
-- EXISTS: each user once, no DISTINCT needed
SELECT u.* FROM users u
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
The second one states the intent correctly, and the planner runs it as a "semi join": it stops as soon as it finds the first matching order.
If you also need the order amount, you use a JOIN (or a subquery with an aggregate), because you can't pull a column out of EXISTS.
You can also write a correlated subquery inside the SELECT:
SELECT u.id, (SELECT max(created_at) FROM orders o WHERE o.user_id = u.id)
FROM users u;
On a small result that's fine, but on a big table it may run a separate query for every row. When in doubt, run EXPLAIN ANALYZE and compare. Don't guess.
Sign up to mark studied questions and save your progress.