Queries and indexes
Ask the database only for what you need, in one round trip where you can. Index for the queries you run, and read the plan before you guess.
- Recommended 5
Recommended
Index the queries you run
DAT-9Add an index for each frequent query's filter, join and sort, and no index that no query uses.
Read the query plan
DAT-10Before you change a slow query or add an index, read its plan. Check again after the change.
Load related rows in one query
DAT-11Never run one query per item in a list. Load related rows together with a join or one
INquery.Select only the columns you use
DAT-12Name the columns a query needs. Avoid
SELECT *in app code.Page through long lists by key
DAT-13For long lists, page by the last key seen instead of
OFFSET. Offsets get slower with every page and skip or repeat rows when data changes.
Read this with
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/queries-and-indexes">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.