Statistics & Cardinality: Functions
Module: Query Optimization & Performance
**View Statistics (PostgreSQL):**
-- View all statistics for a table
SELECT * FROM pg_stats WHERE tablename = 'orders';
-- View specific column statistics
SELECT
attname AS column_name,
n_distinct,
most_common_vals,
most_common_freqs,
histogram_bounds,
correlation,
null_frac
FROM pg_stats
WHERE tablename = 'orders' AND attname = 'status';
-- View table-level statistics
SELECT
relname AS table_name,
reltuples AS estimated_rows,
relpages AS pages
FROM pg_class
WHERE relname = 'orders';
**Check Estimation Accuracy:**
-- Compare estimated vs actual rows
EXPLAIN ANALYZE
SELECT * FROM orders WHERE status = 'active';
-- Output shows:
-- Seq Scan on orders (cost=0..10000 rows=800000)
-- (actual time=0.1..50.2 rows=900000)
-- Estimated: 800K, Actual: 900K, Error: 1.125x
**Update Statistics:**
-- Update all statistics
ANALYZE orders;
-- Update specific columns
ANALYZE orders (status, created_at);
-- Increase statistics detail
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;
**Extended Statistics (Correlated Columns):**
-- Create dependency statistics
CREATE STATISTICS city_state_deps (dependencies)