行数/ドキュメント数を取得(高速)
Oracle
-- Statistics-based (fast, estimated):
SELECT num_rows FROM dba_tables WHERE table_name = 'CUSTOMER';
-- Exact: SELECT COUNT(*) FROM customer;num_rows は最後の ANALYZE/DBMS_STATS 実行時点の値。正確な値には COUNT(*) を使用する。
PostgreSQL
-- Estimated (instant):
SELECT reltuples::bigint FROM pg_class WHERE relname = 'customer';
-- Exact: SELECT count(*) FROM customer;reltuples は最後の ANALYZE/VACUUM 時点の推定値。大きなテーブルでの完全な COUNT は高コスト。
MySQL
-- Estimated (InnoDB):
SELECT table_rows FROM information_schema.tables
WHERE table_name = 'customer';
-- Exact: SELECT COUNT(*) FROM customer;InnoDB の table_rows は推定値で、最大 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(ヒープ)または 1(クラスタ化)で行数が得られる。COUNT(*) スキャンよりはるかに高速。
MongoDB
// Fast (from metadata):
db.customer.estimatedDocumentCount()
// Exact (can count with a filter): db.customer.countDocuments({})estimatedDocumentCount はメタデータを読む(即時)。countDocuments は実際にスキャンを行う。
Redis
DBSIZE
# Specific pattern: count roughly with SCAN (do not use KEYS * in production)DBSIZE は選択中のデータベースのキー総数を O(1) で返す。