Skip to content

Fix order of provider_user index#3347

Merged
dnephin merged 1 commit intomainfrom
dnephin/data-fix-provider-user-index
Oct 3, 2022
Merged

Fix order of provider_user index#3347
dnephin merged 1 commit intomainfrom
dnephin/data-fix-provider-user-index

Conversation

@dnephin
Copy link
Contributor

@dnephin dnephin commented Sep 29, 2022

gorm created the index as PRIMARY KEY (identity_id, provider_id)

Looking at the queries in #3345 we can see that while some queries use a WHERE clause with both of these, two of the queries can use only the provider_id. The order of the columns in the index matters.

https://www.postgresql.org/docs/current/indexes-multicolumn.html has this to say about it (the default index type should be b-tree, even though it's not in the statement, ref).

A multicolumn B-tree index can be used with query conditions that involve any subset of the index's columns, but the index is most efficient when there are constraints on the leading (leftmost) columns. The exact rule is that equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will be used to limit the portion of the index that is scanned. Constraints on columns to the right of these columns are checked in the index, so they save visits to the table proper, but they do not reduce the portion of the index that has to be scanned.

Since this index includes all the rows in the table, we would have to scan the full index if we did not include an identity_id.

We always query with a provider_id, but not always with an identity_id, so re-ordering this index ensures we can always use it optimally.

See https://www.postgresql.org/docs/current/indexes-multicolumn.html

We always query with a provider_id, but not always with an identity_id, so re-ordering this
index ensures we can always use it optimally.
Copy link
Collaborator

@BruceMacD BruceMacD left a comment

Choose a reason for hiding this comment

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

good catch

@dnephin dnephin merged commit de4c4b4 into main Oct 3, 2022
@dnephin dnephin deleted the dnephin/data-fix-provider-user-index branch October 3, 2022 15:26
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