Repository navigation
Do not collate selected columns on Postgres - #989
Merged
hugo-vrijswijk merged 3 commits intoNov 24, 2026
Merged
Conversation
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
left a comment
Contributor
There was a problem hiding this comment.
2 things, one from our robot overlord. But otherwise looks good
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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: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 perUNIONbranch.Fix
Keep sorting under
"C", but return the key plain.DISTINCT ONandORDER BYstay collated, so the order of results is unchanged, and the join can use the index again. Postgres is the only dialect withcollateSelected = true, so other backends are unaffected.Effect
On one of our projects this was analyzed on 9-branch
UNIONover 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.