Skip to content

Instantly share code, notes, and snippets.

@ShikharVj
Created November 21, 2024 12:23
Show Gist options
  • Save ShikharVj/3152a4f67195b7de3560db6a9d58eff7 to your computer and use it in GitHub Desktop.
Save ShikharVj/3152a4f67195b7de3560db6a9d58eff7 to your computer and use it in GitHub Desktop.
The following gist contains the list of Postgres DB queries which can be used to review and identify bottlenecks in the database. These bottlenecks can be large table sizes, sequential scans on tables or unused indexes and much more.
-- Query 1: To identify table and index size for each table
SELECT
relname AS table_name,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
pg_size_pretty(pg_table_size(relid)) AS table_size,
pg_size_pretty(pg_indexes_size(relid)) AS indexes_size
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC;
-- Query 2: To identify which tables are being accessed sequentially or through index scan
SELECT
schemaname || '.' || relname as table,
seq_scan as sequential_scans,
seq_tup_read as sequential_tuples_read,
idx_scan as index_scans,
idx_tup_fetch as index_tuples_fetched,
pg_relation_size(relid) as table_size,
pg_size_pretty(pg_relation_size(relid)) as table_size_pretty,
seq_scan::float / NULLIF(idx_scan, 0) as seq_to_idx_scan_ratio
FROM pg_stat_user_tables
WHERE seq_scan > idx_scan
ORDER BY table_size DESC;
-- Query 3: To review query calls, times, rows and the conditions used in those queries
-- WARNING: This table contains historical data from the last reset.
SELECT
queryid,
query,
calls,
mean_time,
rows--,
-- regexp_matches(query, 'WHERE\s+([^\s]+.*?)(?=\s*(GROUP BY|ORDER BY|LIMIT|$))', 'g') AS where_condition,
-- regexp_matches(query, 'ON\s+([^\s]+.*?)(?=\s*(WHERE|GROUP BY|ORDER BY|LIMIT|$))', 'g') AS on_condition
FROM pg_stat_statements
WHERE mean_time > 1000
ORDER BY calls DESC, mean_time DESC
-- LIMIT 100;
-- Query 4: To review index usage over table or
SELECT
relname AS table_name,
indexrelname AS index_name,
idx_scan AS total_scans,
idx_tup_read AS total_tuples_read,
idx_tup_fetch AS total_tuples_fetched
FROM
pg_stat_user_indexes
-- WHERE
-- relname = 'appointment';
-- idx_scan = 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment