DBAtlas · Atlas de operações de banco de dados

Obter a contagem de linhas / documentos (rápido)

Oracle

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

num_rows reflete a última execução de ANALYZE/DBMS_STATS; use COUNT(*) para um valor exato.

PostgreSQL

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

reltuples é uma estimativa referente ao último ANALYZE/VACUUM; um COUNT completo é caro em tabelas grandes.

MySQL

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

No InnoDB, table_rows é uma estimativa e pode errar em até 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) ou 1 (clustered) fornece a contagem de linhas; muito mais rápido que uma varredura com COUNT(*).

MongoDB

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

estimatedDocumentCount lê metadados (instantâneo); countDocuments faz uma varredura real.

Redis

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

DBSIZE retorna em O(1) o número total de chaves no banco de dados selecionado.

Abrir no DBAtlas →