// SQL snippet

Compare row counts across tables

COUNT each table in one UNION ALL query and, optionally, compute the difference against a baseline or a second environment.

Main statement
All engines

The task

After a migration you want the row census of source and target tables side by side. Counts that match are the cheapest possible integrity signal.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT 'customers' AS table_name, COUNT(*) AS row_count FROM customers
UNION ALL
SELECT 'orders', COUNT(*) FROM orders
UNION ALL
SELECT 'order_items', COUNT(*) FROM order_items
UNION ALL
SELECT 'products', COUNT(*) FROM products
ORDER BY row_count DESC;

Fonctionnement

Each branch counts one table and tags the count with a name; UNION ALL glues them into a small report. There are no joins, and most engines answer COUNT(*) by scanning the smallest index rather than the table, so this is the cheapest integrity check you can run on big data. The variant extends the same pattern to source-versus-target comparisons; when the two sides live in different databases, run each half there and compare the numbers.

Variations

Source vs target with the difference

SELECT s.table_name, s.source_count, t.target_count,
       t.target_count - s.source_count AS difference
FROM (
  SELECT 'customers' AS table_name, COUNT(*) AS source_count FROM customers
  UNION ALL
  SELECT 'orders', COUNT(*) FROM orders
) s
JOIN (
  SELECT 'customers' AS table_name, COUNT(*) AS target_count FROM customers_archive
  UNION ALL
  SELECT 'orders', COUNT(*) FROM orders_archive
) t ON t.table_name = s.table_name;

Questions that come up

Counts match. Can I trust the migration?

Matching counts are necessary but not sufficient: rows can differ in content while counting the same. Treat equal counts as the cheap first gate, then run a checksum or a symmetric difference on the tables that matter before declaring the migration done.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.