Skip to content

Commit

Permalink
advisor: fix included column order in suggested indexes
Browse files Browse the repository at this point in the history
If an index optimizes multiple quals, the previous code wasn't deterministic
and could append the columns from the included quals in any order, which could
lead to a non optimal index suggestion.

To fix, the include quals are not emitted in ascending order of column they
contains, so there's a guarantee that the first columns are in the correct
order.  The result is still not fully deterministic in case of a single qual
having multiple columns not included in a child qual, but this doesn't really
matter as the order is not significant there (at least from the advisor point
of view).

Thanks to disqus user Sivan for the report.
  • Loading branch information
rjuju committed Aug 5, 2024
1 parent bc7edc4 commit b4e3595
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions pg_qualstats--2.1.0.sql
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ BEGIN
filtered AS (
SELECT (qual).relid, amname, coalesce(qualid, qualnodeid) AS parent,
count(*) AS weight,
(array_agg(qualnodeid),
(array_agg(DISTINCT qualnodeid),
array_agg(queryid)
)::@[email protected]_quals AS quals
FROM pgqs
Expand Down Expand Up @@ -628,10 +628,13 @@ BEGIN
v_cur json;
BEGIN
IF rec.included IS NOT NULL THEN
FOREACH v_cur IN ARRAY rec.included LOOP
FOR v_cur IN SELECT v->'qualnodeids'
FROM (SELECT * FROM unnest(rec.included)) AS r(v)
ORDER BY pg_catalog.json_array_length(v->'qualnodeids') ASC
LOOP
-- Direct cast from json to bigint is only possible since pg10
FOR v_qualnodeid IN
SELECT pg_catalog.json_array_elements(v_cur->'qualnodeids')::text::bigint
SELECT pg_catalog.json_array_elements(v_cur)::text::bigint
LOOP
v_quals_todo := v_quals_todo || v_qualnodeid;
END LOOP;
Expand Down

0 comments on commit b4e3595

Please sign in to comment.