---
title: "Queries and indexes · Agent Wranglers"
url: https://agentwranglers.se/playbook/data/queries-and-indexes
updated: 2026-10-20
licence: "All rights reserved"
---

# Queries and indexes

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

> 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.

**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`.

## Required

- [Pass values as parameters](https://agentwranglers.se/playbook/data/queries-and-indexes/parameters): Send every value as a query parameter. Never build SQL by joining strings with input.
- [Index the queries you run](https://agentwranglers.se/playbook/data/queries-and-indexes/index-the-queries-you-run): Add an index for each frequent query's filter, join and sort, and no index that no query uses.
- [Load related rows in one query](https://agentwranglers.se/playbook/data/queries-and-indexes/no-n-plus-one): Never run one query per item in a list. Load related rows together with a join or one `IN` query.

## Recommended

- [Read the query plan](https://agentwranglers.se/playbook/data/queries-and-indexes/query-plans): Before you change a slow query or add an index, read its plan. Check again after the change.
- [Select only the columns you use](https://agentwranglers.se/playbook/data/queries-and-indexes/select-columns): Name the columns a query needs. Avoid `SELECT *` in app code.
- [Page through long lists by key](https://agentwranglers.se/playbook/data/queries-and-indexes/keyset-pagination): For 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.

- Previous: [Schema design](https://agentwranglers.se/playbook/data/schema-design)
- Next: [Transactions and concurrency](https://agentwranglers.se/playbook/data/transactions-and-concurrency)
- [All chapters](https://agentwranglers.se/playbook/data)
