PREP WITH PROOF
Menu
SQL & DATA RECONCILIATION / PRACTICAL GUIDE

SQL INTERSECT vs INNER JOIN: Common Rows, Duplicates and NULL

Choose INTERSECT, INNER JOIN or EXISTS for common rows. Test duplicates, NULL comparisons, composite keys and projections with a complete SQLite lab.

THE QUICK ANSWER

INTERSECT returns distinct rows shared by two selected projections. INNER JOIN returns matching source pairs and can multiply duplicates; EXISTS filters left records without that multiplication. NULL handling and the selected columns can make these results differ even after adding DISTINCT.

What should one output row represent?

Two teams export records and ask for the rows they have in common. One query returns three rows, another returns four copies of one row, and adding DISTINCT still leaves only one row. The disagreement is not necessarily an engine bug. The queries can be answering different questions about identity, multiplicity and missing values.

This guide separates three practical goals: distinct projected values present on both sides, every matching pair of source records, and left-side records that have at least one match. It uses a small reproducible SQLite fixture with duplicate rows and nullable fields, then checks each result explicitly.

The intent is reconciliation, not a general introduction to JOIN syntax or UNION. Before choosing an operator, write down the columns that define a common row, whether repeated occurrences matter, and how missing values should compare. Those decisions determine the expected result before indexes or execution plans enter the discussion.

Start with duplicates, different regions and missing fields

Run this setup in a disposable SQLite database. The two A/east rows on each side create a many-to-many match. B exists in both exports but has a different region, so sharing a code does not imply sharing the projected business row. The NULL/north and C/NULL pairs expose the missing-value decision.

The integer IDs are local source-record identifiers. They are deliberately different between the two exports. This keeps source-record identity separate from the business comparison of code and region. Both text columns use BINARY collation, and every supplied value is text or NULL, giving the equivalence checks below a narrow, explicit domain.

CREATE TABLE left_rows(
  id INTEGER PRIMARY KEY,
  code TEXT COLLATE BINARY,
  region TEXT COLLATE BINARY
);
CREATE TABLE right_rows(
  id INTEGER PRIMARY KEY,
  code TEXT COLLATE BINARY,
  region TEXT COLLATE BINARY
);
INSERT INTO left_rows VALUES
 (1,'A','east'), (2,'A','east'), (3,'B','west'),
 (4,NULL,'north'), (5,'C',NULL), (6,'A','west'), (7,'D','left');
INSERT INTO right_rows VALUES
 (11,'A','east'), (12,'A','east'), (13,'B','east'),
 (14,NULL,'north'), (15,'C',NULL), (16,'E','right');

Use INTERSECT for distinct common projected rows

The first query compares the two-column projections and returns three distinct combinations: NULL/north, A/east and C/NULL. Duplicate occurrences of A/east collapse. The final ORDER BY makes this example readable; do not infer an output-order guarantee merely from the operator name.

Column position matters. Select the same logical fields in the same order on both sides, and use compatible representations. An export containing region then code does not become equivalent because its aliases look familiar. Treat the SELECT lists as the explicit comparison contract.

Adding source IDs changes the question. In this fixture, projecting id, code and region produces no intersection because none of the full three-column rows exists in both exports. That is correct for those selected values. Remove a source-local identifier only when it is intentionally outside the business identity being compared.

SELECT code, region FROM left_rows
INTERSECT
SELECT code, region FROM right_rows
ORDER BY code, region;

Source: SQLite SELECT: joins,compound queries,duplicates and ordering ↗

Use JOIN for matching pairs, and EXISTS for left-side membership

The equality JOIN below produces four A/east rows: two left occurrences multiplied by two right occurrences. Each output row represents a qualifying source pair, even though the selected values look identical. This is useful when pair-level evidence matters, but it is not the same output contract as a distinct intersection.

EXISTS instead asks whether a left row has any qualifying right row. It avoids multiplying that left row by the number of right matches. It does not remove duplicate left occurrences automatically. The null-safe EXISTS query in the complete lab retains left IDs 1, 2, 4 and 5; both A/east records remain identifiable.

Choose the projection according to the goal. If an investigation needs to identify which records matched, selecting a.id and b.id preserves evidence a value-only DISTINCT would erase. If the goal is only a set of shared business values, producing and then deduplicating pair-level evidence may be an unnecessary intermediate step.

Goal in this fixtureResult shapeMultiplicity policy
Distinct common (code,region) values3 rows with INTERSECTOne copy per shared combination
Equality-matching source pairs4 A/east rows with JOINLeft count multiplied by right count
Left records with a null-safe matchIDs 1,2,4,5 with EXISTSKeep each qualifying left record
Distinct equality-JOIN valuesA/east onlyDuplicates removed; NULL policy unchanged
SELECT a.code, a.region
FROM left_rows AS a JOIN right_rows AS b
  ON a.code = b.code AND a.region = b.region
ORDER BY a.id, b.id;

Source: SQLite expressions: NULL-safe IS and EXISTS ↗

DISTINCT does not repair a different NULL comparison

In SQLite compound-query duplicate comparisons, NULL can participate as the same missing value as another NULL. An ordinary equality predicate behaves differently: NULL = NULL does not evaluate to true, so the equality JOIN does not match either nullable pair in the fixture. Adding DISTINCT removes duplicate output rows but does not change that predicate.

The lab includes a distinct JOIN using SQLite’s IS operator for each compared column. Under this fixture’s aligned text-or-NULL domain and BINARY collation, it returns the same three combinations as INTERSECT. This is a demonstrated equivalence for that contract, not a universal rewrite for arbitrary affinities, collations and expressions.

Whether NULL should match is a business decision. A missing product code may represent an unusable identifier rather than a shared entity. If incomplete identities should be excluded, filter them deliberately in both set inputs or the membership predicate. Do not choose a NULL policy accidentally by swapping operators.

Source: SQLite expressions: NULL-safe IS and EXISTS ↗

Run every result against the same controlled data

Save the Python block as common_rows_lab.py and run python common_rows_lab.py. It uses the standard-library sqlite3 module and an in-memory database. The complete setup and all seven queries are included, so the block does not depend on executing earlier examples in a separate session.

The published lab ran on Python 3.12.14 with SQLite 3.53.1 and completed 11 checks. It verifies exact results for distinct intersection, pair multiplication, DISTINCT with ordinary equality, a null-safe rewrite, left-record membership, changed projections and an empty right input. It also checks a delimiter-collision counterexample.

The tests establish query semantics for this dataset. They do not measure production query cost or prove cross-engine plan equivalence. When reproducing the experiment elsewhere, retain the engine version, schema, collation and query text along with the observed output.

import sqlite3

setup = """
CREATE TABLE left_rows(
  id INTEGER PRIMARY KEY,
  code TEXT COLLATE BINARY,
  region TEXT COLLATE BINARY
);
CREATE TABLE right_rows(
  id INTEGER PRIMARY KEY,
  code TEXT COLLATE BINARY,
  region TEXT COLLATE BINARY
);
INSERT INTO left_rows VALUES
 (1,'A','east'), (2,'A','east'), (3,'B','west'),
 (4,NULL,'north'), (5,'C',NULL), (6,'A','west'), (7,'D','left');
INSERT INTO right_rows VALUES
 (11,'A','east'), (12,'A','east'), (13,'B','east'),
 (14,NULL,'north'), (15,'C',NULL), (16,'E','right');
"""
queries = {
    'intersection': """
SELECT code, region FROM left_rows
INTERSECT
SELECT code, region FROM right_rows
ORDER BY code, region
    """,
    'join_equal': """
SELECT a.code, a.region
FROM left_rows AS a JOIN right_rows AS b
  ON a.code = b.code AND a.region = b.region
ORDER BY a.id, b.id
    """,
    'join_distinct': """
SELECT DISTINCT a.code, a.region
FROM left_rows AS a JOIN right_rows AS b
  ON a.code = b.code AND a.region = b.region
ORDER BY a.code, a.region
    """,
    'join_nullsafe': """
SELECT DISTINCT a.code, a.region
FROM left_rows AS a JOIN right_rows AS b
  ON a.code IS b.code AND a.region IS b.region
ORDER BY a.code, a.region
    """,
    'exists_nullsafe': """
SELECT a.id
FROM left_rows AS a
WHERE EXISTS (
  SELECT 1 FROM right_rows AS b
  WHERE a.code IS b.code AND a.region IS b.region
)
ORDER BY a.id
    """,
    'code_only': """
SELECT code FROM left_rows
INTERSECT
SELECT code FROM right_rows
ORDER BY code
    """,
    'ids_included': """
SELECT id, code, region FROM left_rows
INTERSECT
SELECT id, code, region FROM right_rows
    """
}
checks = 0

def expect(actual, expected):
    global checks
    assert actual == expected, (actual, expected)
    checks += 1

with sqlite3.connect(":memory:") as db:
    db.executescript(setup)
    common = [(None, 'north'), ('A', 'east'), ('C', None)]
    expect(db.execute(queries['intersection']).fetchall(), common)
    expect(db.execute(queries['join_equal']).fetchall(), [('A', 'east')] * 4)
    expect(db.execute(queries['join_distinct']).fetchall(), [('A', 'east')])
    expect(db.execute(queries['join_nullsafe']).fetchall(), common)
    expect(db.execute(queries['exists_nullsafe']).fetchall(), [(1,), (2,), (4,), (5,)])
    expect(db.execute(queries['code_only']).fetchall(), [(None,), ('A',), ('B',), ('C',)])
    expect(db.execute(queries['ids_included']).fetchall(), [])

    # Delimiter concatenation can create a false common key.
    expect(db.execute("""
        SELECT 'a|b' || '|' || 'c'
        INTERSECT SELECT 'a' || '|' || 'b|c'
    """).fetchall(), [('a|b|c',)])
    expect(db.execute("""
        SELECT 'a|b', 'c'
        INTERSECT SELECT 'a', 'b|c'
    """).fetchall(), [])

    db.execute('DELETE FROM right_rows')
    expect(db.execute(queries['intersection']).fetchall(), [])
    expect(db.execute(queries['exists_nullsafe']).fetchall(), [])

print(f"PASS: {checks} checks; SQLite {sqlite3.sqlite_version}")

Keep composite keys as separate values

It is tempting to compare code || separator || region as a compact key. The lab shows a collision: the pair a|b with c and the pair a with b|c both concatenate into a|b|c. Their combined strings intersect even though the two-column rows do not.

Compare the columns directly, or use a deliberately specified encoding if an external interface truly requires one field. A separator that happens not to occur in today’s sample is not a reliable identity rule. Type conversions, missing values and escaping introduce further decisions that a simple concatenation hides.

Likewise, do not normalize case, whitespace or numeric formatting in only one branch. If normalization is required, apply the same defined transformation to both inputs and test collisions it can introduce. A broader notion of equality may combine records that must remain separate in the source system.

Check the dialect and equality domain before rewriting

SQLite supports INTERSECT with duplicate removal, while PostgreSQL also documents INTERSECT ALL for duplicate-preserving set intersection. That variant is a different request from a JOIN and is not executed by this SQLite lab. Check the engine’s supported syntax rather than adding ALL on the assumption that every set operator accepts it.

The null-safe predicate syntax also varies by engine. SQLite’s compact IS expression is used here; other systems commonly expose IS NOT DISTINCT FROM or another dialect-specific comparison. Verify its semantics and availability for the database you run.

Mixed storage classes, type affinity and text collation can change comparisons. The aligned TEXT columns in this fixture are intentional. A claim that DISTINCT JOIN always equals INTERSECT needs more evidence than matching row counts on one clean dataset. Include representative types and collation rules before adopting a rewrite.

Source: PostgreSQL combining queries: INTERSECT and ALL ↗

Measure only after the output contract is fixed

Use EXPLAIN QUERY PLAN on the real schema to inspect how SQLite executes the candidate query. Indexes, table sizes, selectivity and statistics can affect the chosen strategy. This guide makes no claim that INTERSECT, JOIN or EXISTS is always faster. Comparing timings for queries that return different meanings does not identify the correct implementation.

Build a small expected-result suite first: duplicates on each side, an unmatched row, a missing value in every key position, an empty input and a composite-key collision. Compare values and multiplicities, not just the number of rows. Then inspect plans and measure with realistic data under the same semantics.

For reconciliation, the useful conclusion is a precise statement of what is common. Use INTERSECT for distinct shared projections, JOIN when source pairs are required, and EXISTS when left-record membership is required. Keep the identity columns and missing-value policy visible so a later optimization cannot silently change the question.

Source: SQLite EXPLAIN QUERY PLAN ↗

KEEP THESE THREE THINGS

Your next steps

  1. Define one output row: shared values, a source pair or a qualifying left record.
  2. Compare the complete intended key and choose NULL behavior explicitly before deduplicating.
  3. Verify values and multiplicities with expected results before comparing execution plans or timings.

Sources & official resources

Linked resources checked on 2026-11-07. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →