// SQL snippet

Row counts of every table

COUNT(*) reads every row, so running it on every table of a big database takes a long time. Each engine keeps a row figure in its catalogs that costs nothing to read and is close enough for dashboards and sanity checks.

Main statement
PostgreSQL
Couvre également
SQL Server MySQL SQLite

The task

You need a rough row census across the whole database right now, and running an exact COUNT(*) against every table would take longer than the answer is worth.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
SELECT relname AS table_name,
       n_live_tup AS approx_row_count
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC;

Fonctionnement

n_live_tup in pg_stat_user_tables is kept up to date from committed inserts and deletes and re-measured by VACUUM and ANALYZE, so reading it costs nothing. It drops to zero after crash recovery or pg_stat_reset() until the next analyze; pg_class.reltuples is the planner's figure and survives both. For exact counts on a handful of tables, run COUNT(*) on those.

Variations

MySQL

MySQL
SELECT table_name, table_rows AS approx_row_count
FROM information_schema.tables
WHERE table_schema = 'mydb' AND table_type = 'BASE TABLE'
ORDER BY table_rows DESC;
-- InnoDB table_rows is sampled and cached for
-- information_schema_stats_expiry; ANALYZE TABLE refreshes it

SQL Server

SQL Server
SELECT t.name AS table_name,
       SUM(ps.row_count) AS approx_row_count
FROM sys.dm_db_partition_stats ps
JOIN sys.tables t ON t.object_id = ps.object_id
WHERE ps.index_id IN (0, 1)
GROUP BY t.name
ORDER BY SUM(ps.row_count) DESC;
-- index 0 (heap) or 1 (clustered index) holds every row once

SQLite

SQLite
-- SQLite keeps no row estimates; count for real, one table at a time
SELECT 'users' AS table_name, COUNT(*) AS row_count FROM users
UNION ALL
SELECT 'orders', COUNT(*) FROM orders;

Questions that come up

How far off can the estimate be?

PostgreSQL's figure is usually within a few percent on tables autovacuum keeps up with. The MySQL manual warns that InnoDB's table_rows can differ from the real count by 40 to 50 percent. SQL Server's row_count is documented as approximate but tracks the actual count closely in practice, since it is maintained as rows are written.

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.