-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathview_pgFirstAid.sql
More file actions
1396 lines (1385 loc) · 52.5 KB
/
view_pgFirstAid.sql
File metadata and controls
1396 lines (1385 loc) · 52.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
create or replace
function pgfirstaid_pg_stat_statements_checks()
returns table (
severity TEXT,
category TEXT,
check_name TEXT,
object_name TEXT,
issue_description TEXT,
current_value TEXT,
recommended_action TEXT,
documentation_link TEXT,
severity_order INTEGER
) as $$
begin
if not exists (
select
1
from
pg_extension
where
extname = 'pg_stat_statements') then
return;
end if;
return query
with pss as (
select
queryid,
query,
calls,
total_exec_time,
mean_exec_time,
rows
from
pg_stat_statements
where
calls > 0
order by
total_exec_time desc
limit 10)
select
'MEDIUM' as severity,
'Query Health' as category,
'Top 10 Queries by Total Execution Time' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'Queries with the highest total execution time are usually the best optimization targets for overall workload improvement' as issue_description,
'calls: ' || pss.calls || ', total_exec_time_ms: ' || round(pss.total_exec_time::numeric, 2) ||
', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 2) || ', rows: ' || pss.rows ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Run EXPLAIN (ANALYZE, BUFFERS) and focus on reducing total runtime for these fingerprints first' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/using-explain.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pss;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'High Mean Execution Time Queries' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'Queries with high average runtime and enough call volume are underperforming and likely user-visible' as issue_description,
'calls: ' || pss.calls || ', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 2) ||
', total_exec_time_ms: ' || round(pss.total_exec_time::numeric, 2) ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Add or improve indexes and rewrite query predicates to reduce per-execution latency' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/using-explain.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 20
and pss.mean_exec_time > 100
order by
pss.mean_exec_time desc
limit 10;
return query
with pss as (
select
queryid,
query,
calls,
temp_blks_read,
temp_blks_written,
total_exec_time
from
pg_stat_statements
where
(temp_blks_read + temp_blks_written) > 0
order by
(temp_blks_read + temp_blks_written) desc
limit 10)
select
'MEDIUM' as severity,
'Query Health' as category,
'Top 10 Queries by Temp Block Spills' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'Frequent temp block usage points to sort or hash operations spilling to disk and causing avoidable latency' as issue_description,
'calls: ' || pss.calls || ', temp_blks_read: ' || pss.temp_blks_read ||
', temp_blks_written: ' || pss.temp_blks_written || ', total_exec_time_ms: ' ||
round(pss.total_exec_time::numeric, 2) || ', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Reduce row width, improve index support for sort or group patterns, and tune work_mem cautiously' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-WORK-MEM \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pss;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'Low Cache Hit Ratio Queries' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'Low buffer cache hit ratio indicates heavy physical reads and likely missing indexes or poor filtering' as issue_description,
'calls: ' || pss.calls || ', cache_hit_pct: ' || round(
100.0 * pss.shared_blks_hit / NULLIF(pss.shared_blks_hit + pss.shared_blks_read, 0),
2
) || ', shared_blks_read: ' || pss.shared_blks_read || ', shared_blks_hit: ' || pss.shared_blks_hit ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Prioritize index tuning and query filtering to reduce disk reads for these statements' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/using-explain.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 20
and (pss.shared_blks_hit + pss.shared_blks_read) > 0
and (100.0 * pss.shared_blks_hit / NULLIF(pss.shared_blks_hit + pss.shared_blks_read, 0)) < 90
order by
(100.0 * pss.shared_blks_hit / NULLIF(pss.shared_blks_hit + pss.shared_blks_read, 0)) asc
limit 10;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'High Runtime Variance Queries' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'High runtime variance can indicate plan instability, skewed data distribution, or parameter sensitivity' as issue_description,
'calls: ' || pss.calls || ', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 2) ||
', stddev_exec_time_ms: ' || round(pss.stddev_exec_time::numeric, 2) ||
', total_exec_time_ms: ' || round(pss.total_exec_time::numeric, 2) || ', query: ' ||
left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Check plan stability with EXPLAIN (ANALYZE, BUFFERS), update statistics, and review parameterized execution paths' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/routine-vacuuming.html \
https://www.postgresql.org/docs/current/using-explain.html' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 20
and pss.stddev_exec_time > pss.mean_exec_time
order by
pss.stddev_exec_time desc
limit 10;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'High Calls Low Value Queries' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'Very high call volume with low per-call value can create avoidable overhead and crowd out expensive work' as issue_description,
'calls: ' || pss.calls || ', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 3) ||
', total_exec_time_ms: ' || round(pss.total_exec_time::numeric, 2) ||
', rows_per_call: ' || round((pss.rows::numeric / NULLIF(pss.calls, 0)), 2) ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Batch repeated requests, cache stable lookups, and reduce N+1 query patterns in the application layer' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 5000
and pss.mean_exec_time <= 2
and (pss.rows::numeric / NULLIF(pss.calls, 0)) <= 2
order by
pss.calls desc
limit 10;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'High Rows Per Call Queries' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'High rows returned per execution often indicates over-fetching or missing selective filters' as issue_description,
'calls: ' || pss.calls || ', rows_per_call: ' || round((pss.rows::numeric / NULLIF(pss.calls, 0)), 2) ||
', total_rows: ' || pss.rows || ', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 2) ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Add tighter predicates, pagination, and narrower SELECT lists to reduce unnecessary row transfer' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/queries-limit.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 20
and (pss.rows::numeric / NULLIF(pss.calls, 0)) > 10000
order by
(pss.rows::numeric / NULLIF(pss.calls, 0)) desc
limit 10;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'High Shared Block Reads Per Call Queries' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'High shared block reads per call usually points to heavy table or index scans and poor locality' as issue_description,
'calls: ' || pss.calls || ', shared_blks_read_per_call: ' || round((pss.shared_blks_read::numeric / NULLIF(pss.calls, 0)), 2) ||
', shared_blks_read: ' || pss.shared_blks_read || ', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 2) ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Use EXPLAIN (ANALYZE, BUFFERS) to add selective indexes and reduce pages read per execution' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/using-explain.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 20
and (pss.shared_blks_read::numeric / NULLIF(pss.calls, 0)) > 1000
order by
(pss.shared_blks_read::numeric / NULLIF(pss.calls, 0)) desc
limit 10;
return query
select
'MEDIUM' as severity,
'Query Health' as category,
'Top Queries by WAL Bytes Per Call' as check_name,
'queryid: ' || pss.queryid::text as object_name,
'High WAL generation per execution can indicate heavy write amplification and expensive update patterns' as issue_description,
'calls: ' || pss.calls || ', wal_bytes_per_call: ' || round(
((to_jsonb(pss)->>'wal_bytes')::numeric / NULLIF(pss.calls, 0)),
2
) || ', wal_bytes_total: ' || round((to_jsonb(pss)->>'wal_bytes')::numeric, 2) ||
', mean_exec_time_ms: ' || round(pss.mean_exec_time::numeric, 2) ||
', query: ' || left(regexp_replace(pss.query, E'[\n\r\t]+', ' ', 'g'), 350) as current_value,
'Reduce row churn, batch writes where possible, and review index maintenance cost for heavy write queries' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://www.postgresql.org/docs/current/wal-intro.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
pg_stat_statements pss
where
pss.calls >= 20
and coalesce((to_jsonb(pss)->>'wal_bytes')::numeric, 0) > 0
and ((to_jsonb(pss)->>'wal_bytes')::numeric / NULLIF(pss.calls, 0)) > 1048576
order by
((to_jsonb(pss)->>'wal_bytes')::numeric / NULLIF(pss.calls, 0)) desc
limit 10;
end;
$$ language plpgsql;
-- Adding dropping of the view instead of replace because of conversion issues with new health checks.
-- This way we start with a fresh view.
drop view if exists v_pgfirstAid;
create view v_pgfirstAid as
-- CRITICAL: Tables without primary keys
select
'CRITICAL' as severity,
'Table Health' as category,
'Missing Primary Key' as check_name,
quote_ident(pt.schemaname) || '.' || quote_ident(tablename) as object_name,
'Table missing a primary key, which can cause replication issues and/or poor performance' as issue_description,
'No primary key defined' as current_value,
'Add a primary key or unique constraint with NOT NULL columns' as recommended_action,
'https://www.postgresql.org/docs/current/ddl-constraints.html' as documentation_link,
1 as severity_order
from
pg_tables pt
where
pt.schemaname not like all(array['information_schema', 'pg_catalog', 'pg_toast', 'pg_temp%'])
and not exists (
select
1
from
pg_constraint pc
join pg_class c on
pc.conrelid = c.oid
join pg_namespace n on
c.relnamespace = n.oid
where
pc.contype = 'p'
and n.nspname = pt.schemaname
and c.relname = pt.tablename
)
union all
-- CRITICAL: Unused indexes consuming significant space
select
'CRITICAL' as severity,
'Table Health' as category,
'Unused Large Index' as check_name,
quote_ident(psi.schemaname) || '.' || quote_ident(psio.indexrelname) as object_name,
'Large unused index consuming disk space and potentially impacting write performance' as issue_description,
pg_size_pretty(pg_relation_size(psi.indexrelid)) || ' (0 scans)' as current_value,
'Consider dropping this index if truly unused after monitoring usage patterns. Never drop an index without validating usage!' as recommended_action,
'https://www.postgresql.org/docs/current/sql-dropindex.html' as documentation_link,
1 as severity_order
from
pg_stat_user_indexes psi
join pg_statio_user_indexes psio on
psi.indexrelid = psio.indexrelid
where
idx_scan = 0
and pg_relation_size(psi.indexrelid) > 104857600
-- 100MB
union all
-- HIGH: Inactive Replication slots
(with q as (
select
slot_name,
plugin,
database,
restart_lsn,
case
when active is true then 'active'
else 'inactive'
end as "status",
pg_size_pretty(
pg_wal_lsn_diff(
pg_current_wal_lsn(), restart_lsn)) as "retained_wal",
pg_size_pretty(safe_wal_size) as "safe_wal_size"
from
pg_replication_slots
where
active = false
)
select
'HIGH' as severity,
'Replication Health' as category,
'Inactive Replication Slots' as check_name,
'Slot name:' || slot_name as object_name,
'Target replication slot is inactive' as issue_description,
'Retained wal:' || retained_wal || ' database:' || database as current_value,
'If the replication slot is no longer needed, drop the slot' as recommended_action,
'https://www.morling.dev/blog/mastering-postgres-replication-slots' as documentation_link,
2 as severity_order
from
q)
union all
-- credit: https://www.morling.dev/blog/mastering-postgres-replication-slots/ -- Thank you Gunnar Morling!
-- HIGH: Tables with high bloat
(with q as (
select
current_database(),
schemaname,
tblname,
bs * tblpages as real_size,
(tblpages-est_tblpages)* bs as extra_size,
case
when tblpages > 0
and tblpages - est_tblpages > 0
then 100 * (tblpages - est_tblpages)/ tblpages::float
else 0
end as extra_pct,
fillfactor,
case
when tblpages - est_tblpages_ff > 0
then (tblpages-est_tblpages_ff)* bs
else 0
end as bloat_size,
case
when tblpages > 0
and tblpages - est_tblpages_ff > 0
then 100 * (tblpages - est_tblpages_ff)/ tblpages::float
else 0
end as bloat_pct,
is_na
from
(
select
ceil( reltuples / ( (bs-page_hdr)/ tpl_size ) ) + ceil( toasttuples / 4 ) as est_tblpages,
ceil( reltuples / ( (bs-page_hdr)* fillfactor /(tpl_size * 100) ) ) + ceil( toasttuples / 4 ) as est_tblpages_ff,
tblpages,
fillfactor,
bs,
tblid,
schemaname,
tblname,
heappages,
toastpages,
is_na
from
(
select
( 4 + tpl_hdr_size + tpl_data_size + (2 * ma)
- case
when tpl_hdr_size%ma = 0 then ma
else tpl_hdr_size%ma
end
- case
when ceil(tpl_data_size)::int%ma = 0 then ma
else ceil(tpl_data_size)::int%ma
end
) as tpl_size,
bs - page_hdr as size_per_block,
(heappages + toastpages) as tblpages,
heappages,
toastpages,
reltuples,
toasttuples,
bs,
page_hdr,
tblid,
schemaname,
tblname,
fillfactor,
is_na
from
(
select
tbl.oid as tblid,
ns.nspname as schemaname,
tbl.relname as tblname,
tbl.reltuples,
tbl.relpages as heappages,
coalesce(toast.relpages, 0) as toastpages,
coalesce(toast.reltuples, 0) as toasttuples,
coalesce(substring(
array_to_string(tbl.reloptions, ' ')
from 'fillfactor=([0-9]+)')::smallint, 100) as fillfactor,
current_setting('block_size')::numeric as bs,
case
when version()~ 'mingw32'
or version()~ '64-bit|x86_64|ppc64|ia64|amd64' then 8
else 4
end as ma,
24 as page_hdr,
23 + case
when MAX(coalesce(s.null_frac, 0)) > 0 then ( 7 + count(s.attname) ) / 8
else 0::int
end
+ case
when bool_or(att.attname = 'oid' and att.attnum < 0) then 4
else 0
end as tpl_hdr_size,
sum( (1-coalesce(s.null_frac, 0)) * coalesce(s.avg_width, 0) ) as tpl_data_size,
bool_or(att.atttypid = 'pg_catalog.name'::regtype)
or sum(case when att.attnum > 0 then 1 else 0 end) <> count(s.attname) as is_na
from
pg_attribute as att
join pg_class as tbl on
att.attrelid = tbl.oid
join pg_namespace as ns on
ns.oid = tbl.relnamespace
left join pg_stats as s on
s.schemaname = ns.nspname
and s.tablename = tbl.relname
and s.inherited = false
and s.attname = att.attname
left join pg_class as toast on
tbl.reltoastrelid = toast.oid
where
not att.attisdropped
and tbl.relkind in ('r', 'm')
group by
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
order by
2,
3
) as s
) as s2
) as s3)
select
'HIGH' as severity,
'Table Health' as category,
'Table Bloat (Detailed)' as check_name,
quote_ident(schemaname) || '.' || quote_ident(tblname) as object_name,
'Table has significant bloat (>50%) affecting performance and storage' as issue_description,
'Real size: ' || pg_size_pretty(real_size::bigint) ||
', Bloat: ' || pg_size_pretty(bloat_size::bigint) ||
' (' || ROUND(bloat_pct::numeric, 2) || '%)' as current_value,
'Run VACUUM FULL to reclaim space' as recommended_action,
'https://www.postgresql.org/docs/current/sql-vacuum.html,
https://github.com/ioguix/pgsql-bloat-estimation/' as documentation_link,
2 as severity_order
from
q
where
bloat_pct > 50.0
and schemaname not like all(array['information_schema', 'pg_catalog', 'pg_toast', 'pg_temp%'])
order by
quote_ident(schemaname),
quote_ident(tblname))
union all
--Credit: https://github.com/ioguix/pgsql-bloat-estimation -- Jehan-Guillaume (ioguix) de Rorthais!
-- HIGH: Tables never analyzed
select
'HIGH' as severity,
'Table Health' as category,
'Missing Statistics' as check_name,
quote_ident(schemaname) || '.' || quote_ident(relname) as object_name,
'Table has never been analyzed, query planner missing statistics' as issue_description,
'Last analyze: Never' as current_value,
'Run ANALYZE on this table or enable auto-analyze' as recommended_action,
'https://www.postgresql.org/docs/current/sql-analyze.html' as documentation_link,
2 as severity_order
from
pg_stat_user_tables pt
where
last_analyze is null
and last_autoanalyze is null
and n_tup_ins + n_tup_upd + n_tup_del > 1000
union all
-- HIGH: Tables larger than 100GB
(with ts as (
select
table_schema,
table_name,
pg_relation_size('"' || table_schema || '"."' || table_name || '"') as size_bytes,
pg_size_pretty(pg_relation_size('"' || table_schema || '"."' || table_name || '"')) as size_pretty
from
information_schema.tables
where
table_type = 'BASE TABLE'
and pg_relation_size('"' || table_schema || '"."' || table_name || '"') > 107374182400
-- 100GB in bytes
order by
size_bytes desc)
select
'HIGH' as severity,
'Table Health' as category,
'Tables larger than 100GB' as check_name,
ts.table_schema || '"."' || ts.table_name as object_name,
'The following table' as description,
ts.size_pretty as current_value,
'I suggest looking into partitioning tables. Do you need all of this data? Can some of it be archived into something like S3?' as recommended_action,
'https://www.heroku.com/blog/handling-very-large-tables-in-postgres-using-partitioning/' as documentation_link,
2 as severity_order
from
ts)
union all
-- HIGH: Duplicate or redundant indexes
-- Compare actual index structure (columns, operator class) not string definitions
select
'HIGH' as severity,
'Table Health' as category,
'Duplicate Index' as check_name,
quote_ident(n1.nspname) || '.' || c1.relname || ': ' || i1.relname || ' & ' || i2.relname as object_name,
'Multiple indexes with identical column sets and operator classes' as issue_description,
'Indexes: ' || i1.relname || ', ' || i2.relname as current_value,
'Review and consolidate duplicate indexes and focus on keeping the most efficient one' as recommended_action,
'https://www.postgresql.org/docs/current/indexes-multicolumn.html' as documentation_link,
2 as severity_order
from
pg_index idx1
join pg_class i1 on idx1.indexrelid = i1.oid
join pg_class c1 on idx1.indrelid = c1.oid
join pg_namespace n1 on c1.relnamespace = n1.oid
join pg_index idx2 on
idx1.indrelid = idx2.indrelid -- same table
and idx1.indexrelid < idx2.indexrelid -- avoid duplicates
and idx1.indkey = idx2.indkey -- same columns
and idx1.indclass = idx2.indclass -- same operator classes
and idx1.indoption = idx2.indoption -- same options
join pg_class i2 on idx2.indexrelid = i2.oid
where
n1.nspname not like all(array['information_schema', 'pg_catalog', 'pg_toast', 'pg_temp%'])
union all
-- HIGH: Table with more than 200 columns
(with cc as (
select
table_schema,
table_name,
COUNT(*) as column_count
from
information_schema.columns
where
table_schema not in ('pg_catalog', 'information_schema')
group by
table_schema,
table_name
order by
column_count desc)
select
'HIGH' as severity,
'Table Health' as category,
'Table with more than 200 columns' as check_name,
cc.table_schema || '.' || cc.table_name as object_name,
'Postgres has a hard 1600 column limit, but that also includes columns you have dropped. Continuing to widen your table can impact performance.' as issue_description,
cc.column_count::text as current_value,
'Yikes-it is about time you put a hard stop on widing your tables and begin breaking this table into several tables. I once worked on a table with over 300 columns before.......' as recommended_action,
'https://www.tigerdata.com/learn/designing-your-database-schema-wide-vs-narrow-postgres-tables \
https://nerderati.com/postgresql-tables-can-have-at-most-1600-columns \
https://www.postgresql.org/docs/current/limits.html' as documentation_link,
2 as severity_order
from
cc
where
cc.column_count > 200)
union all
-- MEDIUM: Blocked and Blocking Queries
(with bq as (
select
blocked.pid as blocked_pid,
blocked.query as blocked_query,
blocking.pid as blocking_pid,
blocking.query as blocking_query,
now() - blocked.query_start as blocked_duration
from
pg_locks blocked_locks
join pg_stat_activity blocked on
blocked.pid = blocked_locks.pid
join pg_locks blocking_locks
on
blocking_locks.transactionid = blocked_locks.transactionid
and blocking_locks.pid != blocked_locks.pid
join pg_stat_activity blocking on
blocking.pid = blocking_locks.pid
where
not blocked_locks.granted)
select
'MEDIUM' as severity,
'Query Health' as category,
'Current Blocked/Blocking Queries' as check_name,
'Blocked PID: ' || bq.blocked_pid || chr(10) ||
'Blocked Query: ' || bq.blocked_query as object_name,
'The following query is being blocked by an already running query' as issue_description,
'Blocking PID: ' || bq.blocking_pid || chr(10) ||
'Blocking Query: ' || bq.blocking_query as current_value,
'Blocked queries are part of concurrency behavior. However, it is always recommended to monitor long running blocking queries. The Crunchy Data article recommended has an excellent walk through and suggested steps on how to tackle unnecessary blocking queries' as recommended_action,
'https://www.postgresql.org/docs/current/explicit-locking.html' as documentation_link,
3 as severity_order
from
bq)
union all
-- MEDIUM: Tables with outdated statistics
(with s as (
select
current_setting('autovacuum_analyze_scale_factor')::float8 as analyze_factor,
current_setting('autovacuum_analyze_threshold')::float8 as analyze_threshold,
current_setting('autovacuum_vacuum_scale_factor')::float8 as vacuum_factor,
current_setting('autovacuum_vacuum_threshold')::float8 as vacuum_threshold
),
tt as (
select
n.nspname,
c.relname,
c.oid as relid,
t.n_dead_tup,
t.n_mod_since_analyze,
c.reltuples * s.vacuum_factor + s.vacuum_threshold as v_threshold,
c.reltuples * s.analyze_factor + s.analyze_threshold as a_threshold
from
s,
pg_class c
join pg_namespace n on
c.relnamespace = n.oid
join pg_stat_all_tables t on
c.oid = t.relid
where
c.relkind = 'r'
and n.nspname not like all(array['information_schema', 'pg_catalog', 'pg_toast', 'pg_temp%'])
)
select
'MEDIUM' as severity,
'Table Health' as category,
'Outdated Statistics' as check_name,
quote_ident(nspname) || '.' || quote_ident(relname) as object_name,
'Table statistics are outdated, which can lead to poor query plans' as issue_description,
'Dead tuples: ' || n_dead_tup || ' (threshold: ' || round(v_threshold) || '), ' ||
'Modifications since analyze: ' || n_mod_since_analyze || ' (threshold: ' || round(a_threshold) || ')' as current_value,
case
when n_dead_tup > v_threshold
and n_mod_since_analyze > a_threshold then 'Run VACUUM ANALYZE'
when n_dead_tup > v_threshold then 'Run VACUUM'
when n_mod_since_analyze > a_threshold then 'Run ANALYZE'
end as recommended_action,
'https://www.postgresql.org/docs/current/routine-vacuuming.html,
https://www.depesz.com/2020/01/29/which-tables-should-be-auto-vacuumed-or-auto-analyzed/' as documentation_link,
3 as severity_order
from
tt
where
n_dead_tup > v_threshold
or n_mod_since_analyze > a_threshold
order by
nspname,
relname)
union all
-- credit: https://www.depesz.com/2020/01/29/which-tables-should-be-auto-vacuumed-or-auto-analyzed -- Thanks depesz!
-- MEDIUM: Low index usage efficiency
select
'MEDIUM' as severity,
'Table Health' as category,
'Low Index Efficiency' as check_name,
quote_ident(schemaname) || '.' || quote_ident(indexrelname) as object_name,
'Index has low scan to tuple read ratio indicating poor selectivity' as issue_description,
'Scans: ' || idx_scan || ', Tuples: ' || idx_tup_read ||
' (Ratio: ' || ROUND(idx_tup_read::numeric / nullif(idx_scan, 0), 2) || ')' as current_value,
'Review index definition and query patterns, consider partial indexes' as recommended_action,
'https://www.postgresql.org/docs/current/indexes-partial.html' as documentation_link,
3 as severity_order
from
pg_stat_user_indexes psi
where
idx_scan > 100
and idx_tup_read::numeric / nullif(idx_scan, 0) > 1000
union all
-- MEDIUM: Replication slots with high wal retation (90% of max wal)
(with q as (
select
slot_name,
plugin,
database,
restart_lsn,
case
when active is true then 'active'
else 'inactive'
end as "status",
pg_size_pretty(
pg_wal_lsn_diff(
pg_current_wal_lsn(), restart_lsn)) as "retained_wal",
pg_size_pretty(safe_wal_size) as "safe_wal_size"
from
pg_replication_slots
where
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) >= (safe_wal_size * 0.9)
)
select
'MEDIUM' as severity,
'Replication Health' as category,
'Replication Slots Near Max Wal Size' as check_name,
'Slot name:' || slot_name as object_name,
'Target replication slot has retained close to 90% of the max wal size' as issue_description,
'Retained wal:' || retained_wal || ' safe_wal_size:' || safe_wal_size as current_value,
'Consider implementing a heartbeat table or using pg_logical_emit_message()' as recommended_action,
'https://www.morling.dev/blog/mastering-postgres-replication-slots' as documentation_link,
3 as severity_order
from
q)
union all
-- MEDIUM: Large sequential scans
select
'MEDIUM' as severity,
'Query Health' as category,
'Excessive Sequential Scans' as check_name,
quote_ident(schemaname) || '.' || quote_ident(relname) as object_name,
'Table has high sequential scan activity, may benefit from additional indexes' as issue_description,
'Sequential scans: ' || seq_scan || ', Tuples read: ' || seq_tup_read as current_value,
'Analyze query patterns and consider adding appropriate indexes' as recommended_action,
'https://www.postgresql.org/docs/current/using-explain.html' as documentation_link,
3 as severity_order
from
pg_stat_user_tables
where
seq_scan > 1000
and seq_tup_read > seq_scan * 10000
union all
-- MEDIUM: Table with more than 50 columns
(with cc as (
select
table_schema,
table_name,
COUNT(*) as column_count
from
information_schema.columns tc
where
table_schema not in ('pg_catalog', 'information_schema')
group by
table_schema,
table_name
order by
column_count desc)
select
'MEDIUM' as severity,
'Table Health' as category,
'Table with more than 50 columns' as check_name,
cc.table_schema || '.' || cc.table_name as object_name,
'Postgres has a hard 1600 column limit, but that also includes columns you have dropped. Continuing to widen your table can impact performance.' as issue_description,
cc.column_count::text as current_value,
'The most straightforward recommendation is to split your table into more tables connected via foreign keys. However, your situation may very based on the type of data stored. Consider the documentation links to learn more.' as recommended_action,
'https://www.tigerdata.com/learn/designing-your-database-schema-wide-vs-narrow-postgres-tables \
https://nerderati.com/postgresql-tables-can-have-at-most-1600-columns \
https://www.postgresql.org/docs/current/limits.html' as documentation_link,
3 as severity_order
from
cc
where
cc.column_count between 50 and 199)
union all
-- MEDIUM: Connection and lock monitoring
select
'MEDIUM' as severity,
'System Health' as category,
'High Connection Count' as check_name,
'Database Connections' as object_name,
'High number of active connections may impact performance' as issue_description,
COUNT(*)::text || ' active connections' as current_value,
'Monitor connection pooling and consider adjusting max_connections' as recommended_action,
'https://www.postgresql.org/docs/current/runtime-config-connection.html' as documentation_link,
3 as severity_order
from
pg_stat_activity
where
state = 'active'
group by
1,
2,
3,
4,
5,
7,
8,
9
having
COUNT(*) > 50
union all
-- MEDIUM: Tables larger than 50GB
(with ts as (
select
table_schema,
table_name,
pg_relation_size('"' || table_schema || '"."' || table_name || '"') as size_bytes,
pg_size_pretty(pg_relation_size('"' || table_schema || '"."' || table_name || '"')) as size_pretty
from
information_schema.tables
where
table_type = 'BASE TABLE'
and pg_relation_size('"' || table_schema || '"."' || table_name || '"') between 53687091200 and 107374182400
order by
size_bytes desc)
select
'MEDIUM' as severity,
'Table Health' as category,
'Tables larger than 100GB' as check_name,
ts.table_schema || '"."' || ts.table_name as object_name,
'The following table' as description,
ts.size_pretty as current_value,
'Tables larger than 50GB should be monitored and reviewed if a data archiving or removal process should be implemented. I suggest looking into partitioning tables, if possible.' as recommended_action,
'https://www.heroku.com/blog/handling-very-large-tables-in-postgres-using-partitioning/' as documentation_link,
3 as severity_order
from
ts)
union all
-- MEDIUM: Queries running longer than 5 minutes
select
'MEDIUM' as severity,
'Query Health' as category,
'Long Running Queries' as check_name,
concat_ws(' | ',
'pid: ' || pgs.pid::text,
'usename: ' || pgs.usename,
'datname: ' || pgs.datname,
'client_address: ' || pgs.client_addr::text,
'state: ' || pgs.state,
'duration: ' || to_char(now() - query_start, 'HH24:MI:SS')
) as object_name,
'The following query has been running for more than 5 minutes. Might be helpful to see if this is expected behavior' as issue_description,
query as current_value,
'Review query using EXPLAIN ANALYZE to identify any bottlenecks, such as full table scans, missing indexes, etc' as recommended_action,
'https://www.postgresql.org/docs/current/using-explain.html' as documentation_link,
3 as severity_order
from
pg_stat_activity pgs
where
state = 'active'
and now() - query_start > interval '5 minutes'
union all
-- MEDIUM: pg_stat_statements extension missing
select
'MEDIUM' as severity,
'Query Health' as category,
'pg_stat_statements Extension Missing' as check_name,
'pg_stat_statements' as object_name,
'pg_stat_statements is not installed, so query fingerprint and workload-level performance checks are unavailable' as issue_description,
'Extension not found in pg_extension' as current_value,
'Self-hosted: add pg_stat_statements to shared_preload_libraries, restart PostgreSQL, then run CREATE EXTENSION pg_stat_statements; AWS RDS: add pg_stat_statements to the parameter group shared_preload_libraries, reboot, then CREATE EXTENSION; GCP Cloud SQL: enable cloudsql.enable_pg_stat_statements, restart if required, then CREATE EXTENSION; Azure Database for PostgreSQL: add pg_stat_statements to shared_preload_libraries, restart, then CREATE EXTENSION' as recommended_action,
'https://www.postgresql.org/docs/current/pgstatstatements.html \
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.Extensions.html \
https://cloud.google.com/sql/docs/postgres/flags \
https://learn.microsoft.com/azure/postgresql/flexible-server/concepts-server-parameters' as documentation_link,
3 as severity_order
where
not exists (
select
1
from
pg_extension
where
extname = 'pg_stat_statements'
)
union all
-- MEDIUM: pg_stat_statements dependent checks
(select
*
from
pgfirstaid_pg_stat_statements_checks())
union all
-- MEDIUM: Top 10 expensive active queries by runtime
(with eq as (
select
pgs.pid,
pgs.usename,
pgs.datname,
pgs.client_addr,
now() - pgs.query_start as runtime,
pgs.query
from
pg_stat_activity pgs
where
pgs.state = 'active'
and pgs.query_start is not null
and pgs.pid <> pg_backend_pid()
and now() - pgs.query_start > interval '30 seconds'
order by
runtime desc
limit 10)
select
'MEDIUM' as severity,
'Query Health' as category,
'Top 10 Expensive Active Queries' as check_name,
concat_ws(' | ',
'pid: ' || eq.pid::text,
'usename: ' || eq.usename,
'datname: ' || eq.datname,
'client_address: ' || coalesce(eq.client_addr::text, 'local'),
'runtime: ' || to_char(eq.runtime, 'HH24:MI:SS')
) as object_name,
'Top 10 active queries running longer than 30 seconds, ordered by runtime. Long-running active queries can signal lock waits, missing indexes, or inefficient plans' as issue_description,
left(regexp_replace(eq.query, E'[\n\r\t]+', ' ', 'g'), 500) as current_value,
'Review these queries with EXPLAIN (ANALYZE, BUFFERS) and reduce lock waits or full scans' as recommended_action,
'https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW \
https://www.postgresql.org/docs/current/using-explain.html \
https://www.tigerdata.com/blog/using-pg-stat-statements-to-optimize-queries' as documentation_link,
3 as severity_order
from
eq)
union all
-- MEDIUM: Lock-wait-heavy active queries
(with lw as (
select
pid,
usename,
datname,
client_addr,
wait_event,
query_start,
now() - query_start as runtime,
query
from
pg_stat_activity
where
state = 'active'
and wait_event_type = 'Lock'
and query_start is not null
and now() - query_start > interval '30 seconds'
and pid <> pg_backend_pid()
order by
runtime desc
limit 10)
select
'MEDIUM' as severity,
'Query Health' as category,
'Lock-Wait-Heavy Active Queries' as check_name,
concat_ws(' | ',
'pid: ' || lw.pid::text,
'usename: ' || lw.usename,
'datname: ' || lw.datname,
'client_address: ' || coalesce(lw.client_addr::text, 'local'),
'wait_event: ' || coalesce(lw.wait_event, 'unknown'),
'runtime: ' || to_char(lw.runtime, 'HH24:MI:SS')
) as object_name,
'Active queries waiting on locks for extended time can block throughput and cause cascading latency' as issue_description,
left(regexp_replace(lw.query, E'[\n\r\t]+', ' ', 'g'), 500) as current_value,
'Reduce transaction duration, enforce consistent lock ordering, and investigate blockers first' as recommended_action,
'https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW \
https://www.postgresql.org/docs/current/explicit-locking.html' as documentation_link,
3 as severity_order
from
lw)
union all
-- MEDIUM: Idle in transaction over 5 minutes
(select