What an Index Is and When Your AI Forgot One

A database index is a sorted shortcut to the rows you search for most, like the index at the back of a book. Without one, the database reads every row in the table to answer a question. With one, it jumps to the right rows. Your AI tool forgets to add them because your app works fine without them until your tables get big.
What does an index actually do?
Say your messages table has 200,000 rows, and your app asks for “the 20 newest messages from user 42.” With no index, Postgres reads all 200,000 rows, keeps the ones where user_id = 42, sorts them, and returns 20. With an index on user_id, it looks up 42 in a sorted list that points straight at those rows.
Here is exactly this, run in a local Postgres (PGlite on a laptop, 200,000 messages across 1,000 users; hosted timings will differ, the ratios are the point). The database’s own report, from explain analyze, was blunt:
Seq Scan on messages (actual time=0.252..17.521 rows=197) Filter: (user_id = 42) Rows Removed by Filter: 199803Execution Time: 17.880 ms“Rows Removed by Filter: 199803” means it read about 200,000 rows to return 197. After create index on messages (user_id) (in a real project, put it in a migration file: see database migrations without losing data), the same query took 0.35 ms. That is the whole idea, and the gap widens as the table grows.
How do I see that an index is missing?
Put explain analyze in front of the slow query and read two lines. In Supabase, run it in the SQL editor:
explain analyzeselect * from messages where user_id = 42 order by created_at desc limit 20;Seq Scanmeans it read the table row by row. On a big table with aFilter:line underneath, that is usually a missing index.Rows Removed by Filteris how much it read and threw away. A big number next to a smallrows=is your answer.Index ScanorBitmap Index Scanmeans an index was used.
Supabase can also point at it: the Query Performance page has an “indexes” tab powered by index_advisor (docs), and the Performance Advisor flags foreign keys with no index (docs).
Which columns did the AI forget?
Four places, in the order to check them:
- Foreign keys. Postgres does not index the column that points at another table. Its docs say the constraint “does not automatically create an index” (PostgreSQL docs).
messages.user_idis the classic. This is also what makes N+1 fixes fast instead of just fewer. - Columns in a
whereyou run on every page.user_id,project_id,slug,email. - Columns your row level security policies filter on. Supabase says to add an index on every column your policies use, because Postgres evaluates the policy against each candidate row and “an unindexed filter column turns a read into a sequential scan” (Supabase RLS docs). Your
auth.uid() = user_idpolicy from row level security explained is running on every query, souser_idneeds an index even if your code never filters by it. - The column you sort by, but together with the filter. See the next section.
Why one index can be right and another useless
Two experiments, same 200,000 rows, same query (where user_id = 42 order by created_at desc limit 20):
| Index | Execution time |
|---|---|
| None | 17.9 ms |
(user_id) | 0.35 ms |
(created_at, user_id) | 1.6 ms |
(user_id, created_at desc) | 0.08 ms |
The third index contains the same two columns as the fourth, just in the other order, and it is twenty times slower. Postgres can only narrow an index scan using its leading columns (PostgreSQL docs). With created_at first, it walks the newest messages and checks each for user 42 until it finds twenty. With user_id first, it jumps to user 42 and the rows are already in date order. Put the column you filter by with = first, the column you sort by second.
The other thing nobody tells you: an index does not mean it gets used. In the same run, a boolean archived column that was 95% true had an index. Asking for archived = true still did a full table scan (58 ms), because reading almost everything through an index is slower than just reading everything. Asking for the rare false side used the index (4.8 ms). Indexes help when the query picks out a small slice. A column with two values is rarely worth one.
What does an index cost?
Every insert and update maintains every index on the table, and each takes disk space, so do not index everything “just in case.” Supabase’s Performance Advisor has an “unused index” check for the ones that never earn their keep (Supabase advisors).
On a live table with real traffic, a plain create index blocks writes until it finishes. create index concurrently avoids that, takes longer, and cannot run inside a transaction block (PostgreSQL docs). On a table with a few thousand rows, plain is fine. In a Supabase migration file, put it alone in its own file; if supabase db push still says it cannot run inside a transaction block, run that statement in the SQL editor. That Supabase behavior was not tested.
Prove it with a test
A test that only checks the rows returned passes with or without an index. You need two. One checks behavior: what the user sees. The other guards the property you are fixing: the lookup does not read the whole table. The behavior test is what protects you when a later change, say “just make it faster,” quietly returns the wrong rows or drops the sort.
This was run in a scratch project (npm i @electric-sql/pglite, "type": "module" in package.json, then node --test). It has three small files. The query:
export async function latestMessages(db, userId) { const { rows } = await db.query( 'select id, user_id, body from messages where user_id = $1 order by created_at desc limit 20', [userId]) return rows}The indexes file, empty on purpose, because this is the app the AI gave you:
export const indexes = []And the tests:
import { test } from 'node:test'import assert from 'node:assert/strict'import { PGlite } from '@electric-sql/pglite'import { latestMessages } from './messages.js'import { indexes } from './indexes.js'
async function seed() { const db = new PGlite() await db.exec(` create table messages ( id serial primary key, user_id int not null, created_at timestamptz not null, body text not null); -- 50,000 messages spread over 500 users, oldest first insert into messages (user_id, created_at, body) select (g % 500) + 1, now() - ((50000 - g) || ' minutes')::interval, 'message ' || g from generate_series(1, 50000) g; `) for (const sql of indexes) await db.exec(sql) await db.exec('analyze messages') return db}
test('a user sees only their own 20 newest messages, newest first', async () => { const db = await seed() const rows = await latestMessages(db, 7) assert.equal(rows.length, 20) assert.ok(rows.every((r) => r.user_id === 7)) const ids = rows.map((r) => r.id) assert.deepEqual(ids, [...ids].sort((a, b) => b - a))})
test('the lookup does not read the whole table', async () => { const db = await seed() const { rows } = await db.query( 'explain (format json) select id, user_id, body from messages where user_id = 7 order by created_at desc limit 20') const plan = JSON.stringify(rows[0]['QUERY PLAN']) assert.ok(!plan.includes('Seq Scan'), 'Postgres is scanning every row of messages') // The planner's own cost estimate on this data: about 71 with (user_id, created_at desc), // about 261 with (created_at, user_id). Tune the ceiling for your table. const cost = JSON.parse(plan)[0].Plan['Total Cost'] assert.ok(cost < 150, `the plan costs ${cost}, the index column order is probably wrong`)})Run node --test with the empty indexes.js. The first test passes. The second fails:
ok 1 - a user sees only their own 20 newest messages, newest firstnot ok 2 - the lookup does not read the whole table error: 'Postgres is scanning every row of messages'Now put the fix in indexes.js:
export const indexes = [ 'create index messages_user_created_idx on messages (user_id, created_at desc)',]Both pass. The cost line guards the column-order lesson. With the wrong order, (created_at, user_id), there is no Seq Scan, so a plain Seq Scan check passes, but this test fails: the plan costs 263.77, the index column order is probably wrong. The ceiling of 150 fits this seeded table; measure your own good plan and set it about twice as high. And if a later “optimization” breaks the behavior, a change from desc to asc fails test 1 and leaves the index test green. That is why you want both.
Two honest limits. The test seeds 50,000 rows because on a tiny table Postgres correctly prefers a full scan, and the plan test would be meaningless. And it checks the plan Postgres chose on your test data, not how fast your production database is. It catches “the index is gone”, which is the failure that matters.
A prompt to find them
List every table in my schema. For each, show its existing indexes, its foreign key columns, and the columns used in its row level security policies. Then search my code for the
whereandorder byclauses my app runs most often. Tell me which of those columns have no index, and rank them by how big the table is likely to get. Do not create anything yet. For each one you recommend, write a test first that fails today (one for behavior, one that checks the query plan does not use a Seq Scan on a seeded table and uses the index you created), show it failing, then add the index and show it passing.
The one check an engineer does by hand
Take the three slowest or busiest queries your app runs, put explain analyze in front of each, and read for Seq Scan with a large Rows Removed by Filter. Do it against a copy of your data that is big enough to matter, not the five rows in your dev database. It is one of the checks behind why your app gets slower with every new user, and item 10 of the launch checklist.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.