获取行数 / 文档数(快速)
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) 返回所选数据库中的键总数。