Sobes.tech
Middle

Why are indexes needed? Explain using an example of a composite index (userId, updatedAt): three queries — by userId, by userId+updatedAt, and only by updatedAt. Where will the index be used?

sobes.tech AI

Answer from AI

Indexes are needed to speed up data retrieval in a database by reducing the number of rows to scan.

Consider a composite index on (userId, updatedAt):

  • Query by userId — the index will be used because userId is the first column in the index.
  • Query by userId + updatedAt — the index will be effective because it matches the order of columns in the index.
  • Query only by updatedAt — the index will not be used because in a composite index, userId comes first, and updatedAt without userId cannot be used for searching.

In summary: a composite index is useful for queries starting with the first column of the index but not for queries that use only subsequent columns.