# SQL queries for comparing tables

Learn which SQL queries compare two tables, find missing or changed rows, and reconcile data with JOIN, EXCEPT, and UNION, with clear examples.

SQL queries for comparing tables rely on EXCEPT, outer JOINs, or UNION to expose rows that differ. Each method answers a different question: missing rows, changed values, or a full side-by-side view. Pick the method by what you need to see, then match rows on a reliable key. 

- Use EXCEPT to list rows in one table that are absent from the other.
- Use a FULL OUTER JOIN on a key to see missing and changed rows together.
- Compare on a stable key, not on row order or display names.
- Handle NULL values explicitly, because a plain equals test does not match two NULLs.
- Run counts and checksums first to see whether a detailed comparison is needed.
 

## What a SQL table comparison can tell you 

A SQL table comparison answers one of three questions about two sets of rows. The first question asks which rows exist in one table but not the other. The second asks which matching rows hold different values in one or more columns. The third asks for a combined view that labels every row by where it appears. 

Choosing the question first keeps a comparison query short and its output readable. A query built for missing rows says nothing about changed prices or edited descriptions. A query built for changed values needs a key that pairs each row with its counterpart. Mixing goals in one statement tends to produce results that are hard to check. 

A key is the column or set of columns that identifies a row uniquely. Product codes, listing IDs, or a pair such as supplier and model number can serve as keys. Without a reliable key, SQL can only compare whole rows as exact copies. Any small edit then makes a row look both deleted and newly added. 

## Finding missing rows with EXCEPT 

The EXCEPT operator returns rows from the first query that do not appear in the second. A basic form reads SELECT id, name, price FROM table_a EXCEPT SELECT id, name, price FROM table_b. Both queries must list the same number of columns in the same order. Their data types must also be compatible column by column. 

EXCEPT works in one direction only, so a full check needs two queries. Running table_a EXCEPT table_b shows rows that exist only in table_a. Swapping the order shows rows that exist only in table_b. Some database systems, such as Oracle, use the keyword MINUS for the same operation. 

EXCEPT compares entire rows across every selected column, which makes it strict. A row with one changed price appears in both directions as a mismatch. Duplicate rows also disappear from an EXCEPT result, much as they do with DISTINCT. Where duplicates matter, some systems offer EXCEPT ALL, which keeps repeated rows in the count. 

## Comparing row values with a FULL OUTER JOIN 

A FULL OUTER JOIN on a shared key compares the data of two tables row by row. The join keeps every row from both sides, matched where the keys agree. Rows without a partner show NULL in every column from the missing side. A WHERE clause then filters the output down to rows that differ. 

A typical filter checks for a missing key on either side or a changed value. One pattern reads WHERE a.id IS NULL OR b.id IS NULL OR a.price <> b.price. Each extra column you care about adds another OR condition to that clause. A CASE expression can label each row as only in A, only in B, or changed. 

The join approach shows old and new values next to each other in one result. That layout suits reviews where a person needs to see exactly what changed. Some databases, MySQL among them, do not support FULL OUTER JOIN as a keyword. In those systems, a LEFT JOIN combined through UNION with a RIGHT JOIN gives the same result. 

## Using UNION ALL to find differences in one pass 

UNION ALL with GROUP BY finds rows that differ between two tables in a single query. Each source is selected with an extra column naming its table, then the results are stacked. A GROUP BY over all compared columns collapses identical rows into one group. HAVING COUNT(*) = 1 keeps only the rows that appear on one side. 

The pattern needs no join key, which helps when tables lack a clean identifier. MIN or MAX of the source column then shows which table holds each unmatched row. Grouping also treats NULL values as equal, which avoids a trap of plain comparisons. Duplicate rows inside one table can distort the counts, so remove them first or count per source. 

The stacked output suits SQL queries for comparison data in reports and audits. Every unmatched row appears once, tagged with the table it came from. A changed row appears twice, once with its old values and once with its new ones. Sorting by key and source places those two versions on adjacent lines. 

## Handling NULLs, data types, and stray spaces 

NULL values need special handling in any SQL comparison that uses equals or not-equals. In standard SQL, a.price <> b.price returns unknown when either value is NULL. The WHERE clause drops unknown results, so a change from NULL to a value goes unseen. Some systems offer IS DISTINCT FROM, which treats two NULLs as equal and NULL versus a value as different. 

Where IS DISTINCT FROM is missing, COALESCE can stand in with a placeholder value. COALESCE(a.price, -1) <> COALESCE(b.price, -1) compares both columns with NULL replaced by -1. The placeholder must be a value that cannot appear in the real data. Otherwise a genuine -1 would look identical to a NULL and hide a real difference. 

Data types and formatting cause false mismatches even when the underlying values agree. Trailing spaces, mixed letter case, and different decimal precision can all count as differences to SQL. TRIM, LOWER or UPPER, and CAST to a shared type remove those surface differences. Apply the same cleanup to both tables so the comparison stays fair. 

## Quick reconciliation checks before row-level work 

Data reconciliation checks confirm whether two tables match before you compare individual rows. A row count on each table is the fastest first test. Sums of numeric columns, such as total price or total quantity, flag changed values with little effort. Matching totals do not prove the tables are identical, yet mismatched totals do prove a difference. 

Hash checksums extend the same idea to whole rows or whole tables. A hash function turns a row's values into a short fingerprint string. Comparing fingerprints is faster than comparing every column when tables are wide. Function names differ by system, such as MD5, HASHBYTES, or CHECKSUM. 

A staged approach keeps large comparisons manageable and points you to the problem quickly. Start broad with counts and totals, then narrow to groups such as category or supplier. Run the row-level query only on groups whose totals disagree. Large tables compare faster when the join key has an index, a structure that speeds up lookups. 

- Compare row counts on both tables
- Compare sums of key numeric columns
- Compare totals grouped by a category column
- Compare row hashes for groups that disagree
- Run EXCEPT or a FULL OUTER JOIN on the remaining rows
 

## Choosing the right comparison method 

The right SQL comparison method depends on the question and on what your tables contain. EXCEPT fits a quick check for missing or altered rows when columns line up exactly. A FULL OUTER JOIN fits reviews that need old and new values side by side. UNION ALL with GROUP BY fits tables without a dependable key. 

Database support also shapes the choice of a table comparison query. Some systems lack FULL OUTER JOIN, and some lack EXCEPT ALL or IS DISTINCT FROM. A query that runs on one system may need rewriting for another. Checking the documentation for your database version avoids errors at run time. 

Query performance becomes a factor in the choice as tables grow large. Joins on an indexed key tend to run efficiently on big tables. Set operators may sort or hash every row, which consumes memory and time. Testing each approach on a sample of the data shows how it behaves on your system. 
| Method | Answers | Needs a key | Watch for | 
| EXCEPT | Rows in one table but not the other | No | Runs in one direction, removes duplicates | 
| FULL OUTER JOIN | Missing rows and changed values side by side | Yes | NULL handling in value checks | 
| UNION ALL with GROUP BY | Rows unique to either table in one pass | No | Duplicate rows within a table | 
| Counts and checksums | Whether the tables differ at all | No | Does not show which rows differ |  

## Comparing listing tables when building a shortlist 

Table comparison in SQL helps keep a shortlist accurate when listing data changes over time. Saving a snapshot of your listings lets you compare it against a fresh import later. An EXCEPT query then reveals listings that were removed or newly added. A FULL OUTER JOIN on listing ID shows which prices, specs, or availability values moved. 

Side-by-side shortlists also benefit from joining your own notes to the source listings. A LEFT JOIN from listings to a notes table keeps every listing, even unrated ones. Rows with NULL in the notes columns show options you have not reviewed yet. Keeping notes in a separate table lets a fresh import replace listings without touching your notes. 

Listings from different sources may use different keys and column names. A mapping table that links each source ID to your own ID makes comparison possible. Normalizing units, currency formats, and naming before the comparison reduces false mismatches. Once columns line up, one comparison query can place every option side by side. 

## SQL table comparison questions 

### How do I compare two tables in SQL to find differences? 

Running EXCEPT in both directions or a FULL OUTER JOIN on a key compares two SQL tables. EXCEPT lists whole rows that appear in only one of the tables. The join shows missing rows and changed values together in the same result. 

### What is the difference between EXCEPT and NOT EXISTS? 

EXCEPT compares entire rows, while NOT EXISTS compares only the columns named in its subquery condition. NOT EXISTS keeps duplicates from the outer table and lets you match on a key alone. EXCEPT treats NULL values as equal, whereas a NOT EXISTS condition with equals does not. 

### Can I compare tables in two different databases? 

Yes, tables in two databases can be compared if one query can reach both of them. Systems on the same server often allow a database name prefix in the table reference. Across servers, a remote connection feature or a copied table makes the comparison possible. Names for remote connection features differ by database system, such as linked servers or foreign data wrappers. 

### Why does my comparison query miss rows with NULL values? 

Comparisons miss rows with NULL because equals and not-equals return unknown when either side is NULL. The WHERE clause discards unknown results, so those rows drop out of the output. IS DISTINCT FROM, or COALESCE with a placeholder value, makes the check NULL-aware. 

### How do I compare only certain columns between two tables? 

Comparing certain columns only means listing just those columns in each SELECT before EXCEPT. In a join, the WHERE clause tests only the columns that matter to you. Leaving out timestamps or audit fields keeps routine updates from appearing as differences.
