Intermediate SQL 4 : Advanced SQL Joins and UNION — WHERE vs. ON, Multi-Key Joins, Self Joins, and Stacking Tables: A Practical Reference
Hello everyone! Welcome back to the Intermediate SQL series.
In the previous post, we learned how to connect multiple tables side-by-side using INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Once you start writing multi-table queries at work, though, you quickly run into edge cases that basic equality joins (ON a.id = b.id) cannot solve on their own.
What happens when you add a filter to a LEFT JOIN and suddenly lose all your NULL rows? How do you join events that happened within a specific time window rather than on an exact match? What if you need to compare two events inside the same table, or stack two split tables on top of each other?
In this post, we are going to tackle five practical patterns that separate beginner join queries from production-grade SQL: filtering in WHERE vs. ON, joining with comparison operators, joining on multiple keys, Self Joins, and stacking datasets with UNION and UNION ALL.
Quick Cheat Sheet: Side-by-Side Joins vs. Vertical Stacking
Before diving into the queries, here is a quick mental map of how these five techniques fit together:
| Technique | Direction / Mechanism | Key Clause | When to Reach for It |
|---|---|---|---|
Filter in ON |
Side-by-side (pre-join filter) | LEFT JOIN ... ON ... AND ... |
Filtering the right table before joining while keeping all left-table rows |
Filter in WHERE |
Side-by-side (post-join filter) | LEFT JOIN ... WHERE ... |
Filtering the final combined result set after matches are already built |
| Comparison Join | Side-by-side (non-equi join) | ON a.id = b.id AND b.date > a.date |
Matching events across date ranges, thresholds, or relative timelines |
| Multi-Key Join | Side-by-side (composite key) | ON a.k1 = b.k1 AND a.k2 = b.k2 |
Enforcing uniqueness on composite keys or helping composite indexes run faster |
| Self Join | Side-by-side (same table twice) | FROM tbl a JOIN tbl b ON ... |
Comparing sequential rows, hierarchies, or before/after events in one table |
UNION / UNION ALL |
Vertical stacking | SELECT ... UNION ALL SELECT ... |
Appending rows from two separate queries with matching column schemas |
Filtering in WHERE vs. ON: The Classic LEFT JOIN Trap
This is one of the most common bugs in analytics SQL. Normally, we put row filters inside the WHERE clause. When you are writing an INNER JOIN, putting a condition in ON versus WHERE produces the exact same output. In a LEFT JOIN, however, placement changes everything.
Let’s stick with our Crunchbase dataset (tutorial.crunchbase_companies and tutorial.crunchbase_acquisitions). Here is our baseline LEFT JOIN:
SELECT
companies.permalink AS companies_permalink,
companies.name AS companies_name,
acquisitions.company_permalink AS acquisitions_permalink,
acquisitions.acquired_at AS acquired_date
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_acquisitions acquisitions
ON companies.permalink = acquisitions.company_permalink
ORDER BY 1;
Now suppose we want to exclude acquisition details for /company/1000memories. Watch what happens when we add that condition inside the ON clause:
SELECT
companies.permalink AS companies_permalink,
companies.name AS companies_name,
acquisitions.company_permalink AS acquisitions_permalink,
acquisitions.acquired_at AS acquired_date
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_acquisitions acquisitions
ON companies.permalink = acquisitions.company_permalink
AND acquisitions.company_permalink != '/company/1000memories'
ORDER BY 1;
Because AND acquisitions.company_permalink != '/company/1000memories' sits inside ON, SQL evaluates it before gluing the tables together. You can think of it as a filter applied only to the right table (acquisitions). As a result, /company/1000memories still appears in your output from companies, just with NULL in acquisitions_permalink and acquired_date.
Now move that exact same condition down into the WHERE clause:
SELECT
companies.permalink AS companies_permalink,
companies.name AS companies_name,
acquisitions.company_permalink AS acquisitions_permalink,
acquisitions.acquired_at AS acquired_date
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_acquisitions acquisitions
ON companies.permalink = acquisitions.company_permalink
WHERE acquisitions.company_permalink != '/company/1000memories'
OR acquisitions.company_permalink IS NULL
ORDER BY 1;
In the WHERE clause, filtering happens after the two tables have already been joined:
/company/1000memoriesis wiped out from the result set completely—even on thecompaniesside.- Notice that we had to explicitly add
OR acquisitions.company_permalink IS NULL. Without that extra check,WHERE acquisitions.company_permalink != '/company/1000memories'would also drop every unacquired company (becauseNULL != '/company/1000memories'evaluates to unknown in SQL), accidentally converting yourLEFT JOINinto anINNER JOIN!
Pro Tip: Whenever you filter on a column from the right table of a
LEFT JOIN, ask yourself: “Do I want to drop the unmatched left rows completely (WHERE), or keep all left rows and only restrict which right rows attach to them (ON)?”
Putting LEFT JOIN + WHERE Together on One-to-Many Data
Let’s bring in a third Crunchbase table: tutorial.crunchbase_investments, which stores one row per funding event (meaning a single company can appear multiple times across different funding rounds or investors). If we want to count unique investors for every startup headquartered in New York (state_code = 'NY'), filtering on the left table in WHERE works safely without dropping New York companies that have zero recorded investors:
SELECT
companies.name AS company_name,
companies.status,
COUNT(DISTINCT investments.investor_name) AS unique_investors
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_investments investments
ON companies.permalink = investments.company_permalink
WHERE companies.state_code = 'NY'
GROUP BY 1, 2
ORDER BY 3 DESC;
Joining with Comparison Operators (>, <, BETWEEN)
So far, every ON clause we have written has used an equals sign (=) to match exact keys. In SQL, however, the ON clause accepts any boolean conditional expression—including >, <, >=, <=, and !=.
This is especially useful when analyzing date windows or sequential milestones. For instance, suppose we want to count how many investments each Crunchbase company received more than 5 years after it was founded:
SELECT
companies.permalink,
companies.name,
companies.status,
COUNT(investments.investor_permalink) AS investors
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_investments_part1 investments
ON companies.permalink = investments.company_permalink
AND investments.funded_year > companies.founded_year + 5
GROUP BY 1, 2, 3;
Notice how our WHERE vs. ON rule applies here too! Because investments.funded_year > companies.founded_year + 5 is inside ON, startups with zero late-stage investments still stay in the output with investors = 0. If we moved that comparison into WHERE, every startup without an investment after Year 5 would disappear from the report.
Joining on Multiple Keys: Accuracy and Performance
Sometimes matching on a single column isn’t enough. You can chain multiple join keys together inside ON using AND:
SELECT
companies.permalink,
companies.name,
investments.company_name,
investments.company_permalink
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_investments_part1 investments
ON companies.permalink = investments.company_permalink
AND companies.name = investments.company_name;
There are two practical reasons to join on multiple keys in production pipelines:
- Data Accuracy (Composite Keys): In many transactional tables, a single column isn’t unique on its own. For example, if you join a regional branch table to a sales table,
branch_codemight repeat across regions—so you must join on bothregion_idandbranch_codeto prevent false many-to-many row explosions. - Query Performance (Composite Indexes): Even when the first key (
permalink) is already unique, adding a second key (name) can occasionally help the database query optimizer use a multi-column index on huge warehouse tables, avoiding full table scans. (On smaller datasets, the speed difference is negligible, so prioritize clarity first.)
Self Joins: Joining a Table to Itself
A Self Join sounds intimidating at first, but it is just a regular JOIN where both sides point to the exact same table using two different aliases.
Whenever you need to compare one row in a table against another row in that same table—such as employee-to-manager hierarchies, before-and-after status changes, or sequential customer actions—a Self Join is the cleanest tool for the job.
Suppose we want to find startups in tutorial.crunchbase_investments_part1 that received an investment from Great Britain ('GBR') after previously receiving an investment from Japan ('JPN'):
SELECT DISTINCT
japan_investments.company_name,
japan_investments.company_permalink
FROM tutorial.crunchbase_investments_part1 japan_investments
JOIN tutorial.crunchbase_investments_part1 gb_investments
ON japan_investments.company_name = gb_investments.company_name
AND gb_investments.investor_country_code = 'GBR'
AND gb_investments.funded_at > japan_investments.funded_at
WHERE japan_investments.investor_country_code = 'JPN'
ORDER BY 1;
Look at how clean that reads once you assign descriptive aliases (japan_investments and gb_investments):
- Both aliases point to
tutorial.crunchbase_investments_part1. - The
ONclause matches rows belonging to the same company where the British investment occurred chronologically later (gb_investments.funded_at > japan_investments.funded_at). SELECT DISTINCTensures that if a company had multiple Japanese or British investors, it only appears once in our final list.
UNION vs. UNION ALL: Stacking Datasets Vertically
Every JOIN we have covered so far combines tables horizontally (adding new columns side-by-side). UNION, on the other hand, stacks the results of two separate SELECT queries vertically—one on top of the other.
In our Crunchbase database, the investments dataset is split across two partitions: tutorial.crunchbase_investments_part1 and tutorial.crunchbase_investments_part2. To combine them into one unified table, use UNION ALL:
SELECT *
FROM tutorial.crunchbase_investments_part1
UNION ALL
SELECT *
FROM tutorial.crunchbase_investments_part2;
UNION vs. UNION ALL: Always Know the Difference
UNION(Deduplicates): Appends the second query’s rows and then scans the entire combined dataset to drop any exact duplicate rows. Because deduplication requires sorting or hashing in memory,UNIONis noticeably slower on large tables.UNION ALL(Keeps Everything): Simply appends all rows from the second query directly beneath the first without checking for duplicates. In day-to-day analytics and ETL pipelines, you will useUNION ALL95% of the time because it is faster and preserves true row counts.
Three Strict Rules for UNION Queries
Before SQL will stack two SELECT statements together, both queries must pass three schema checks:
- Same number of columns: Every
SELECTblock in theUNIONmust return the exact same column count. - Matching data types in the same order: Column 1 in the first query must match the data type of Column 1 in the second query, Column 2 must match Column 2, and so on.
- Column names come from the first
SELECT: SQL names the output columns using the aliases from your top query.
Because each SELECT statement runs independently before being stacked, you can apply different filters or even tag each partition with a hardcoded label column before combining them:
SELECT
'part_1' AS dataset_source,
company_permalink,
company_name,
investor_name
FROM tutorial.crunchbase_investments_part1
WHERE company_name ILIKE 'T%'
UNION ALL
SELECT
'part_2' AS dataset_source,
company_permalink,
company_name,
investor_name
FROM tutorial.crunchbase_investments_part2
WHERE company_name ILIKE 'M%';
In Summary
We just rounded out the full SQL join and set-stacking toolkit! Keep these rules of thumb handy whenever your queries span multiple tables or partitions:
- Mind
ONvs.WHEREinLEFT JOINs: Filter the right table insideONto preserve unmatched left rows; filter inWHEREonly when you want to discard rows from the final joined output. - Use non-equi joins (
>,<,BETWEEN) insideONwhenever you need to align events across date windows rather than exact IDs. - Alias clearly in Self Joins (
early_eventvs.later_event) so comparing two rows from the same table reads like plain English. - Default to
UNION ALLwhen stacking partitioned tables vertically, savingUNIONstrictly for cases where removing duplicate rows is required.
With joins and aggregations under your belt, you now have all the core building blocks of Intermediate SQL! In the next chapter, we will wrap up Intermediate SQL by combining everything—aggregations, GROUP BY, HAVING, CASE logic, and multi-table joins—into real end-to-end analytical queries. See you in the next post!
“In God we trust. All others must bring data.”
– W. Edwards Deming
Read next
-
From Intermediate SQL
Intermediate SQL 3 : SQL Joins Explained — INNER, LEFT, RIGHT, and FULL OUTER: A Practical ReferenceTime to connect the dots across multiple tables! In this post, we break down how relational joins work under the hood and walk through INNER, LEFT,...
-
From Intermediate SQL
Intermediate SQL 2 : SQL Aggregate Functions and DISTINCT: A Practical ReferenceMoving from raw rows to real summaries! In this post, we break down COUNT, SUM, MIN, MAX, AVG, and DISTINCT using our Apple (AAPL) stock dataset—in...
-
From Intermediate SQL
Intermediate SQL 1 : Getting Started & The DatasetKicking off the Intermediate SQL series! Moving past basic SELECT queries, multiple ways to solve problems, and exploring the Apple stock dataset.
-
More Data Engineering
Introduction SparkLet’s learn how to use Spark with Python by using the pyspark library! Make sure to view the video lecture explaining Spark and RDDs before continu...
-
Reader favourite
Dota 2 Patch 7.42 : Item Potency, 15-Minute Tormentors, and Day 1 Meta ShiftsDota 2 Patch 7.42 kills passive high-ground stalling, nerfs spell burst, and adds Item Potency. Here is a full breakdown plus Day 1 pick and win ra...
-
Reader favourite
How to Research Anything (Even When You Have a Full-Time Job)You don't need a PhD or endless free time to do deep research. Here is a practical system to scope questions, filter sources, and actually finish w...
-
Reader favourite Predicting BBRI Stocks with Meta’s ProphetThe IHSG so shit recently not gonna lie/ Have you ever wondered how businesses predict future sales, how weather apps forecast the temperature, or ...
-
Reader favourite
How to get your personal Dota2 DataThis is going to be a short post. This is really interesting for me personally. As a Data Scientist and avid Dota 2 player, what could be better th...
Leave a comment