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.
- Required 3
- Recommended 3
Required
Pass values as parameters
RequiredSend every value as a query parameter. Never build SQL by joining strings with input.
Index the queries you run
RequiredAdd an index for each frequent query's filter, join and sort, and no index that no query uses.
Load related rows in one query
RequiredNever run one query per item in a list. Load related rows together with a join or one
INquery.
Recommended
Read the query plan
RecommendedBefore you change a slow query or add an index, read its plan. Check again after the change.
Select only the columns you use
RecommendedName the columns a query needs. Avoid
SELECT *in app code.Page through long lists by key
RecommendedFor 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.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers data playbook: https://agentwranglers.se/playbook/data/queries-and-indexes.