composite index: An index on multiple columns. Order matters — it can serve queries that use a leftmost prefix of the columns. A composite index covers several columns, such as (customer_id, created_at). The database sorts by the first column, then by the second within each value of the first. The order of columns is everything. This index helps a query that filters on customer_id, or on customer_id and created_at together. It does not help a query that only filters on created_at, just as a phone book sorted by surname does not help you find everyone named Jan.
What should you keep in mind with composite index?
Put the column used for exact matches first and the range or sort column last. One well-chosen composite index can replace several single-column indexes and speed up common queries like "this customer's latest orders". Use EXPLAIN to check which index a query really uses.
What does an example of composite index look like?
CREATE INDEX idx_orders_user_date ON orders (user_id, created_at);
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and schedule