
- Was this photo uploaded by Alan? No.
- Was this photo uploaded by Alan? No.
- …

- An index is a data structure (commonly a B-tree) that maps values in a column to the row locations where those values appear.
- Think of it like the index at the back of a book: instead of reading every page, you look up a keyword and jump directly to the relevant pages.
posted_by column in photo_details, the database can quickly determine that Alan’s photos are at row 822, row 15,000, and row 100,000, and then fetch only those rows.

- The planner checks available indexes for columns used in
WHERE,JOIN,ORDER BY, orGROUP BY. - If a matching index exists, the planner uses it to find row pointers quickly.
- The database fetches only those rows, avoiding unrelated rows and reducing I/O.

- Create a simple single-column index:
- Create a composite index (useful when queries filter on multiple columns). Column order matters:
- PostgreSQL covering index example (stores extra columns in the index so the query can be satisfied from the index alone):
- Use monitoring and the database’s query planner to identify slow queries first.
- Run
EXPLAINorEXPLAIN ANALYZEto see how a query is executed and which columns are causing scans. - Add an index targeted specifically to fix that query pattern (e.g.,
WHERE,JOIN, orORDER BYcolumns). - Re-measure and iterate.
Index the columns used by your slow queries—typically those in
WHERE, JOIN, ORDER BY, and GROUP BY. Use EXPLAIN / EXPLAIN ANALYZE and slow-query logs to identify which queries will benefit before adding an index.- Start with the primary key index only (or a minimal set).
- Monitor performance: slow-query logs, APM tools, or profiling.
- For a slow query, run
EXPLAIN/EXPLAIN ANALYZEand inspect the execution plan. - Add an index targeted to the query pattern (single-column, composite, or covering).
- Re-run the query and observe performance and write impact; iterate as needed.
Do not create indexes blindly. Adding many indexes increases write latency and storage cost. Start with no or few indexes, identify slow queries, and add indexes targeted at those queries only.
- EXPLAIN query plans: https://www.postgresql.org/docs/current/using-explain.html
- B-tree indexes overview: https://www.postgresql.org/docs/current/indexes-types.html
- General guide to database indexing: https://use-the-index-luke.com/