Document opened before the LIMIT
Claim: Performance
A SELECT with an ORDER BY that no index serves sorts its rows before its LIMIT keeps the first ones. Postgres computes the select list below that sort, so an expression in it runs on every row the sort orders, including the rows the LIMIT then discards. When the expression opens a large jsonb value, removing keys with - or #-, reading one with -> or ->>, jsonb_set, || or a cast to text, each of those rows is decompressed whole. A column returned as stored carries only a pointer through the sort, and opens nothing.
Example
Section titled “Example”SELECT project_queries.id, rep.optimizationFROM project_queriesLEFT JOIN LATERAL ( SELECT crq.optimization - 'explainPlan' - 'optimizedExplainPlan' AS optimization FROM ci_runs_queries crq JOIN ci_runs cr ON cr.id = crq.ci_run_id LEFT JOIN ci_repo_configs cfg ON lower(cfg.repo) = lower(cr.repo) WHERE cr.project_id = project_queries.project_id AND crq.hash = project_queries.hash ORDER BY (cr.branch = cfg.comparison_branch) DESC NULLS LAST, crq.created_at DESC, crq.id DESC LIMIT 1) rep ON trueWHERE project_queries.project_id = $1;The leading sort key compares two joined tables, so no index serves the ORDER BY. The lateral keeps one run per query, but its sort orders every run of that query, and the keys come out of each run’s document first. On a restored Query Doctor instance it sorted about 270,000 runs to keep about 720, from a column whose values average 38 KB rendered. The full queries list, which selects more columns around this lateral, took 24.9 s and 29.0 s. In production it took 114.5 s.
The planner charges nothing for decompressing a value, so the plan’s cost does not show this.
How to fix it
Section titled “How to fix it”Return the column unchanged from the subquery, and apply the expression in the SELECT that reads it:
SELECT project_queries.id, rep.optimization - 'explainPlan' - 'optimizedExplainPlan'FROM project_queriesLEFT JOIN LATERAL ( SELECT crq.optimization ... LIMIT 1) rep ON true...The full queries list then took 4.2 s, twice, and returned the same 262 MB. In production it took 13.8 s.
When the ORDER BY and LIMIT are on the outermost SELECT, move them into a subquery that returns the column unchanged, apply the expression in a SELECT around it, and repeat the ORDER BY there. SQL does not promise that a subquery’s order reaches the caller. Postgres does not merge a subquery with a LIMIT into the query around it, so the expression then runs only on the rows the LIMIT keeps. On the same restore, a query sorting about 2,400 rows to keep 10 took 17.8 ms and 49 ms with the keys removed in its select list, and 3.9 ms and 5.0 ms wrapped.
Detection
Section titled “Detection”Query Doctor reports this Finding from the SQL text, the explain plan and the column statistics, when all of these hold:
- A
SELECTwith anORDER BYand aLIMIT, and noDISTINCT,GROUP BYorHAVING, applies-,#-,->,->>,#>,#>>,||,jsonb_set,jsonb_insert,jsonb_strip_nulls,jsonb_pretty,jsonb_extract_path(or its_textandjson_forms), or a cast totext,varcharorjson, to a column of a table in its ownFROM. - The
ORDER BYdoes not sort by that expression, which the sort would need computed. - Postgres computes the select-list entry below the sort. It moves an entry past the sort, onto the rows the
LIMITkeeps, when the entry is volatile or costs more than ten operators: a call torandom(), a function such asto_tsvectoror one written in PL/pgSQL or SQL (cost 100 unless declared), or eleven chained-. When the plan was captured withVERBOSE, the sort’sOutputsays where the expression ran. Otherwise an entry that calls a function whose cost Query Doctor does not know is not reported. - The plan has a Sort directly under the
LIMIT, and the sort reads the column’s table itself, not through a nested subquery with its ownLIMIT. An index that hands rows over in order lets theLIMITstop the scan, and nothing is opened past it. - The column is
jsonorjsonb, and its values average at least 2,000 bytes, as measured from the data by the Collector. A column whose size was not measured is not reported. - At the plan’s row estimates, the documents the
LIMITdiscards, over every run of the subquery, add up to at least 334, about 5 ms at 15 µs each. A row whose value is null opens nothing and is not counted. - When
pg_stat_statementstimed the query in production, one execution takes 5 ms or more on average.
An expression in a SELECT that no LIMIT cuts runs on the rows it returns. A read in a condition, an aggregate or a sort key of such a SELECT is covered by JSON field read on every row.