SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
SQL Joins Deep Dive: Anti-Joins (`NOT EXISTS` vs `NOT IN`).
senior LevelCode ExampleDatabases & SQL
In Simple Words:
- Inner Join: Returns rows with matching keys in both tables.
- Left Outer Join: Returns all rows from left table, with
NULLs for non-matching right rows. - Anti-Join: Finds records in Table A that have no matching record in Table B.
- Performance Rule: Prefer
NOT EXISTSoverNOT IN! If the subquery inNOT INcontains even a singleNULLvalue,NOT INreturns zero rows due to SQL three-valued logic (TRUE,FALSE,UNKNOWN), whileNOT EXISTShandlesNULLs safely and allows the optimizer to use an Anti-Hash Join.
sql
-- Optimal Anti-Join pattern using NOT EXISTS
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.user_id = u.id
);