{"success":true,"name":"check-the-index-before-shipping-a-query-that-filters-or-sort","description":"Just wrote a DB query with a filter, search, or sort on a big table","category":"ai-brimind","path":"ai-brimind/check-the-index-before-shipping-a-query-that-filters-or-sort/SKILL.md","file":"SKILL.md","content":"---\nname: check-the-index-before-shipping-a-query-that-filters-or-sort\ndescription: \"Just wrote a DB query with a filter, search, or sort on a big table\"\n---\n\n# Check the Index Before Shipping a Query That Filters or Sorts\n\n## When to use\nJust wrote a DB query with a filter, search, or sort on a big table\n\n## Example request\nLogin looks up users by email with no index on email → the DB reads every user row on every login; a full 'collection scan' hides fine at 100 users and melts at 100,000. Order list filters by userId and sorts by date → an index on (userId, date) makes it instant; without it the DB scans and sorts everything on each page load. Adding indexes on every field 'just in case' → every write now updates all of them and storage bloats; indexes are targeted tools for real query patterns, not sprinkles. Query is on a tiny config table of 10 fixed rows → scanning is fine, an index adds nothing; index work is for tables that grow.\n\n## Instructions\nAct as a developer who never ships a query without knowing HOW the database will execute it — filters that 'work' can still read every row in the table. For each query you just wrote that filters, searches, or sorts, do this: (1) Name the exact fields the query filters or sorts by. Those fields are index candidates. (2) Check what indexes actually exist — look at the schema definitions, the migration files, or ask the DB directly (getIndexes() in MongoDB, the table's index list in SQL). Do not assume; assumed indexes are the most common invisible performance bug. (3) If no index covers the query and the table will grow, add one on purpose: the filtered field, or a compound index matching 'filter first, sort second' for combined queries. Name the trade-off out loud: indexes speed reads but slightly slow writes and take space, which is why you add the ones your queries need, not one per field. (4) When unsure whether the DB uses the index, ask it to explain itself — explain() in MongoDB or EXPLAIN in SQL — and read whether it reports an index scan or a full scan. That output is evidence; your feeling that 'it seems fast' on dev data is not, because dev tables are tiny. (5) Skip all of this for small fixed tables that will never grow — say so and move on. Only ship once you can state which index serves this query, or give the concrete reason none is needed — 'it worked when I clicked around' is not a reason, it is just a small table.\n\n## Metadata\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #191\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}