Explain Codes LogoExplain Codes Logo

How to Return Rows from Left Table Not Found in Right Table?

sql
join
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 16, 2024
TLDR

Fetch missing rows from the left table using a LEFT JOIN where the matching column in the right table is NULL:

/* Here we are sifting for gold (aka our missing records) in the wild west of SQL! */ SELECT l.* FROM left_table l LEFT JOIN right_table r ON l.id = r.id WHERE r.id IS NULL;

This SQL line-up calls forth all records from left_table that are playing hide and seek in right_table.

Breakdown and variations

Utilizing 'NOT EXISTS' for large data sets

If your data set is looking like a skyline with tall skyscrapers (aka large amount of data), the NOT EXISTS method often gets the job done faster due to better indexing. It's like having a fast sports car in the world of SQL:

/* Using NOT EXISTS is like having a master list of all the kids who didn't turn up for class. Bingo! */ SELECT l.* FROM left_table l WHERE NOT EXISTS ( SELECT 1 FROM right_table r WHERE l.id = r.id );

But remember, proper indexing on your WHERE clause columns is like ensuring your sports car has a good engine.

'NOT IN' for simpler syntax

Sometimes, when you are dealing with those smaller datasets or when you have a list of discrete values, NOT IN is your friend. It's like SQL's own little way of saying, "Nah, I'm taking the day off!":

/* We're just politely asking if l.id is playing truant in the right_table. No big deal, right? */ SELECT l.* FROM left_table l WHERE l.id NOT IN ( SELECT r.id FROM right_table r );

However, awaits some homework. When dealing with nullable columns, be cautious as NOT IN can yield surprising results.

Nitty-gritty details and peculiarities

Join types and their nuances

Developing a clear understanding of LEFT, RIGHT, and FULL join types is essential for handling table comparisons. It's like knowing your chess moves.

Tackling common column names

Dealing with tables having similar column names is like handling twins. Use table aliases and column qualification to tell them apart!

Debugging complex queries

For handling complex queries, use table variables or CTEs for breaking them into digestible chunks. It's like having your pizza slice by slice, not all at once.