Skip to content

Do not collate selected columns on Postgres - #989

Merged
hugo-vrijswijk merged 3 commits into
typelevel:mainfrom
cquiroz:pg-uncollated-selected-columns
Nov 24, 2026
Merged

hugo-vrijswijk merged 3 commits into
typelevel:mainfrom
cquiroz:pg-uncollated-selected-columns

Conversation

@cquiroz

@cquiroz cquiroz commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Background

A collation is the set of rules a database uses to compare and sort text. Grackle sorts text keys with COLLATE "C" (byte order) so the order of rows is the same in SQL and in Scala. An index, on the other hand, is sorted under the column's own collation, and Postgres only uses it when the comparison runs under that same collation.

Problem

When paging on a text key, the subquery that picks the keys of the page sorts by the key under "C", which is needed, but also returns the key labelled "C", which is not:

INNER JOIN (
  SELECT DISTINCT ON ((root.id COLLATE "C")) (root.id COLLATE "C") AS id_alias_0
  FROM root ORDER BY (root.id COLLATE "C") LIMIT 1
) AS root_pred ON (root_pred.id_alias_0 = root.id)

The join back to the table then compares under "C" instead of the column's collation, so Postgres will not use the key's index and scans the whole table, once per UNION branch.

Fix

Keep sorting under "C", but return the key plain. DISTINCT ON and ORDER BY stay collated, so the order of results is unchanged, and the join can use the index again. Postgres is the only dialect with collateSelected = true, so other backends are unaffected.

Effect

On one of our projects this was analyzed on 9-branch UNION over a 30k-row table: execution drops from 170 ms to 68 ms, and sequential scans of the parent table from 12 to 3.

Disclosure

Debugging was AI assisted as well as the production of the PR code.

A paging subquery returned its text key as COLLATE "C", so the join back to the parent table could not use the key's index and fell back to a sequential scan. Keep the collation on DISTINCT ON and ORDER BY only.

@hugo-vrijswijk hugo-vrijswijk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 things, one from our robot overlord. But otherwise looks good

@hugo-vrijswijk hugo-vrijswijk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks

@hugo-vrijswijk
hugo-vrijswijk merged commit a799adb into typelevel:main Nov 24, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants