DBAtlas · Database operations atlas

Get the row / document count (fast)

Oracle

-- Statistics-based (fast, estimated):
SELECT num_rows FROM dba_tables WHERE table_name = 'CUSTOMER';
-- Exact: SELECT COUNT(*) FROM customer;

num_rows reflects the last ANALYZE/DBMS_STATS run; use COUNT(*) for an exact value.

PostgreSQL

-- Estimated (instant):
SELECT reltuples::bigint FROM pg_class WHERE relname = 'customer';
-- Exact: SELECT count(*) FROM customer;

reltuples is an estimate as of the last ANALYZE/VACUUM; a full COUNT is expensive on large tables.

MySQL

-- Estimated (InnoDB):
SELECT table_rows FROM information_schema.tables
WHERE table_name = 'customer';
-- Exact: SELECT COUNT(*) FROM customer;

In InnoDB, table_rows is an estimate and can be off by up to 50%.

SQL Server

SELECT SUM(row_count) AS rows
FROM sys.dm_db_partition_stats
WHERE object_id = OBJECT_ID('dbo.customer')
  AND index_id IN (0, 1);

index_id 0 (heap) or 1 (clustered) gives the row count; much faster than a COUNT(*) scan.

MongoDB

// Fast (from metadata):
db.customer.estimatedDocumentCount()
// Exact (can count with a filter): db.customer.countDocuments({})

estimatedDocumentCount reads metadata (instant); countDocuments performs an actual scan.

Redis

DBSIZE
# Specific pattern: count roughly with SCAN (do not use KEYS * in production)

DBSIZE returns the total number of keys in the selected database in O(1).

Open in DBAtlas →