PostgreSQL Trying to make sense of query plans. Looking for opinions on how I draw them
I've been trying to figure out the best way to make sense of a query, how it affects the database and whether there is room to improve it. I'm a visual person. If something has a diagram I understand it faster, and I wanted the same thing when I work with a database at work or on side projects. I want to see how the data is being retrieved or updated without working it out from the EXPLAIN text.
I've came up with following visual rule:
- Each scan, join and sort is a bar. The band between two bars is as wide as the number of rows flowing through. Width is
1.2 + 0.55 x (log10 rows)², capped between 1.5px and 34px. Linear made anything under 100,000 rows a hairline, and plain log made 1,000 and 1,000,000 look too close. - When the planner's estimate is off from the actual count by more than 2×, the band gets a dashed line showing the estimate. At 10x it gets a label. Postgres has no opinion on 10×, that number is mine.
- Each scan gets a wheel showing how much of the table's pages it touched and in what order, based on
pg_stats.correlationwith a 0.8 cutoff for "in order". - To get the analyzed plan it re-runs the query inside
BEGINandROLLBACKwith a 5 minutestatement_timeout. Writes stop at the estimate unless you opt in.
There's in depth rulebook here.
I would really appreciate some feedback here, I kind of struggling what's the best way to visualize this. Any idea/critique here is most appreciated. Thanks
34
Upvotes


4
u/ArielCoding 26d ago
Looks like the bands stop getting wider at some point, and they maybe look the same size, try sizing the bands relative to the biggest step in each query, so the largest one is always full width and everything else scales from there.
1
u/MrRoy_SQL 26d ago
this looks really nice, the log-squared width is a smart fix for the hairline problem. few things i'd think about:
1
u/Significant_Tune9219 26d ago
The dashed band when the estimate is off is the right signal, but a bad estimate usually starts at one node and then every parent looks wrong too. I'd mark only the deepest node where actual and estimate cross your 2x line, and leave the parents solid. Otherwise the diagram shouts at the join when the scan's selectivity was the real problem. One caution on the re-run: EXPLAIN ANALYZE inside BEGIN and ROLLBACK still executes the statement, so a function with a side effect is not undone by the rollback. The plan can also differ from production if that session's work_mem isn't what the app uses, so I'd print those settings next to the picture.