1 min read

Counting table row counts in PostgreSQL

An easy way to count the number of rows in a PostgreSQL table and sort by totals allowing you to find what's taking up space in your database.

Counting table row counts in PostgreSQL
Isaac Bythewood Isaac Bythewood
2022-05-28

I sometimes find myself running into the problem of hunting down what is taking up a lot of rows in PostgreSQL due to service row restrictions. There is a choice of increasing my service plan but I sometimes find it unnecessary if I have a rogue app just adding a lot of data that can be purged. This happens a lot of logs and security apps tracking login attempts. To find the number of rows used in a PostgreSQL database and order it by count you can run this in psql.

SELECT nspname AS schemaname,relname,reltuples
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
AND relkind='r'
ORDER BY reltuples DESC;

If this runs correctly you should see a sorted list of tables with their row counts. From there you can create a script to purge the offending apps on a schedule if you don't need older data.


Some posts in similar tags to this one.

Optimizing SQLite for Django in production
Optimizing SQLite for Django in production
Django's default SQLite settings are fine for development but will hit "database is locked" errors under any concurrency. This is the config I run in production.
Isaac Bythewood Isaac Bythewood
2026-04-18
Why not make your own dashboard in 2026
Why not make your own dashboard in 2026
I was reflex checking the same six tabs all day so I built one page that has all of it on it, and the part that surprised me is how little work that is now.
Isaac Bythewood Isaac Bythewood
2026-09-10
It's Go all the way down
It's Go all the way down
Every process in front of my websites is a Go binary now, from the tunnel to the web server to the sites themselves, and the whole stack runs on a desktop I already owned for a few dollars a month in power.
Isaac Bythewood Isaac Bythewood
2026-08-30