StoicBuilder

HandbookV the OfficinaIndexes and slow queries

Vthe Officina, Use the tools

Indexes and slow queries

1 min readUpdated 28 November

In plain words

An index is a sorted lookup a database keeps for a column, so finding rows by that column means jumping straight to them instead of reading the whole table.

Where you see it

QuickBite's order history loaded instantly with 200 orders and takes six seconds with 200,000. Supabase's Performance Advisor flags foreign keys with no index, its Query Performance page lists your slowest queries, and explain analyze in the SQL Editor shows why each one is slow.

Supabase SQL Editordatabase
explain analyzeselect * from orders where customer_id = '8f14e45f-...' order by created_at desc limit 20;-- Seq Scan on orders: Postgres read all 200,000 rows to find 20 create index orders_customer_created_idx on orders (customer_id, created_at desc);-- run it again: Index Scan using orders_customer_created_idx
Seq Scan means the whole table was read. With the index, Postgres jumps straight to that customer's newest orders.

What goes wrong

  1. Assuming foreign keys come with an index

    Postgres indexes primary keys on its own, but not the columns that point at other tables, like orders.customer_id. Those are often the columns every page filters by.

  2. Forgetting the column your access rules use

    A row-level security policy such as auth.uid() = user_id runs on every query. Without an index on user_id, every page slows down as the table grows.

  3. Indexing every column to be safe

    Each index is updated on every insert and update, and takes disk space. Add them for queries you actually run, and check they get used.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Find the slowest queries this app runs and show me the explain analyze output for each. Add an index only where it turns a full table scan into an index scan, as a migration, and show me the timings before and after.

Quick check

Sign in to earn +10 XP for it

Guildhall's member list took 0.1 seconds at launch and takes 5 seconds now, with 300,000 members. The query filters by guild_id. Likely fix?

Got a prompt that touches indexes and slow queries?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.