When a PostgreSQL table is small, a query can feel instant. As the table grows, the same query may begin reading far more rows than it needs. An index can help the database find matching rows faster, but adding indexes at random is not a performance strategy. Every index also takes storage and adds work to writes.

The reliable approach is to start with a real slow query, understand its filters and sort order, choose an index that matches that access pattern, and measure the result. This guide explains how PostgreSQL indexes work, when to use common index types, and how to apply the same process to a Supabase project.

What is a PostgreSQL index?

An index is a separate data structure that helps PostgreSQL locate rows without checking every row in a table. Think of a book index: instead of reading every page to find a subject, you use the index to locate likely pages. A database index serves a similar purpose, although the planner still decides whether using it is cheaper than scanning the table.

The default index type is B-tree. It is a strong starting point for common equality and range comparisons, and it can also help with ordering. Primary-key and unique constraints automatically create an index to enforce uniqueness. A foreign-key constraint does not automatically index the referencing column, so that side of a relationship may need attention when joins or parent-row deletes are slow.

Indexes are not free. PostgreSQL must maintain them when indexed values change, and they consume disk space and memory. The goal is not to have the most indexes; it is to have the right indexes for queries the application actually runs.

1. Start with the slow query, not the column

Before creating an index, identify the exact query that is slow and how often the application runs it. Look at its WHERE conditions, join keys, ORDER BY, and LIMIT. Those details describe the access pattern an index needs to support.

In Supabase, use the Query Performance tools to find expensive or frequently executed queries. You can also inspect a SQL query directly with PostgreSQL's EXPLAIN command. A plan shows whether PostgreSQL expects to use a sequential scan, an index scan, a bitmap scan, and what other operations are involved.

EXPLAIN
SELECT id, score, created_at
FROM public.exam_results
WHERE student_id = '00000000-0000-0000-0000-000000000000'
ORDER BY created_at DESC
LIMIT 20;

A sequential scan is not automatically a problem. If a table has only a few rows, or a query needs a large portion of the table, reading the table directly can be cheaper than walking an index and fetching many table rows. Do not treat every sequential scan as a bug.

Read the estimated row counts and the plan nodes around the scan. If estimates are far from reality, table statistics or data distribution may be part of the problem. PostgreSQL's cost values are planner units, not milliseconds. Compare plans and measured execution behavior rather than interpreting a cost number as elapsed time.

2. Match the index to the query

Imagine a student dashboard that repeatedly loads the latest exam results for one student. The query filters by student_id, sorts by created_at, and returns only the newest 20 rows. A composite B-tree index can support that pattern:

CREATE INDEX exam_results_student_created_at_idx
ON public.exam_results (student_id, created_at DESC);

The first column narrows the search to one student. The second column helps return that student's results in the requested time order. This is more targeted than creating unrelated single-column indexes and hoping the planner combines them efficiently.

After creating the index, inspect the plan again:

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, score, created_at
FROM public.exam_results
WHERE student_id = '00000000-0000-0000-0000-000000000000'
ORDER BY created_at DESC
LIMIT 20;

EXPLAIN ANALYZE executes the statement and reports actual row counts and timing. It is useful for measuring a read query, but remember that it really runs the statement: using it on an UPDATE, DELETE, or other write can change data. Test write statements in a safe environment or use a transaction that you roll back, following the PostgreSQL documentation.

3. Understand composite index column order

A composite index stores more than one key column in a defined order. For a B-tree index, conditions on the leading, leftmost columns are especially important. An index on (tenant_id, created_at) is a natural fit for queries that first restrict a tenant and then sort or filter by date.

That same index is not a general-purpose replacement for an index on created_at alone. A query that filters only by the second column may not benefit in the same way. Design the column order from the queries you need to support, and verify the plan rather than applying a universal rule.

For example, if a multi-tenant application frequently runs:

SELECT id, created_at
FROM public.audit_events
WHERE tenant_id = '00000000-0000-0000-0000-000000000000'
  AND created_at >= TIMESTAMPTZ '2026-01-01'
ORDER BY created_at DESC
LIMIT 50;

an index beginning with tenant_id followed by created_at matches the equality filter and date range. If your workload also has queries that filter by date without a tenant, measure those separately before adding another index.

4. Use partial indexes for a frequent subset

A partial index includes only rows that match a condition. This can be useful when an application repeatedly queries a small, well-defined subset, such as open support tickets or pending orders.

CREATE INDEX orders_pending_created_at_idx
ON public.orders (created_at DESC)
WHERE status = 'pending';

This index is smaller than an index containing every order when only a subset has the pending status. The query must contain a condition PostgreSQL can recognise as matching the index predicate. If the application asks for all statuses, or its condition does not imply the predicate, the partial index may not be usable.

5. Choose an index type that fits the data

  • B-tree: The default choice for equality, range comparisons, and many sorting patterns. Start here for ordinary IDs, dates, status filters with useful selectivity, and foreign-key lookups.
  • GIN: Often appropriate for membership and containment searches over values such as arrays, JSONB documents, or full-text search, when the operator class matches the query.
  • BRIN: Useful for very large tables where a column's values correlate with the physical order of rows. An append-heavy event table with timestamps is a common pattern to evaluate.
  • GiST: Supports specialised search strategies, including geometric and range-related operations. Choose it for the operator and data type you actually use, not as a generic replacement for B-tree.

The index type matters because different types support different operators and query patterns. Check the PostgreSQL documentation for the relevant operator class and test with the real query before deploying a specialised index.

6. Do not forget Supabase Row Level Security

Supabase applications often query tables through the Data API while Row Level Security (RLS) policies restrict which rows a user can access. Policy conditions can become part of the work PostgreSQL must do for a request. Supabase recommends indexing columns used by policy filters and checking that a composite B-tree index places the filtered column in a usable leading position.

For example, if a policy repeatedly checks whether a row belongs to the signed-in user, an index on the ownership column may help:

CREATE INDEX enrollments_user_id_idx
ON public.enrollments USING btree (user_id);

Do not change or weaken an RLS policy just to make a query faster. Keep the access rule correct, inspect the query plan with the policy in place, and add an index only when the measured workload justifies it. Our website security checklist also explains why database permissions and server-side access controls matter.

7. Avoid over-indexing

Creating an index for every column can make a database slower to maintain. Inserts, deletes, and updates may need to update multiple index structures. Extra indexes also consume storage and can compete for cache space.

  • Do not add an index just because a column exists.
  • Check whether a primary-key or unique index already covers the access pattern.
  • Look for duplicate or overlapping indexes before creating another one.
  • Be cautious with columns that have only a few distinct values; an index may not help when a query returns a large share of the table.
  • Review whether an index is used by the real workload, not only by one hand-picked query.

Foreign-key columns deserve a deliberate review. PostgreSQL automatically indexes the referenced primary or unique key, but it does not automatically index the referencing column. If the application frequently joins through that column or deletes parent rows, an index on the referencing side may help. It is still a workload decision, not a rule to index every foreign key blindly.

A practical PostgreSQL index workflow

  1. Find the query: Identify the slow or high-volume query from monitoring or application logs.
  2. Read its plan: Use EXPLAIN and, where safe, EXPLAIN ANALYZE to inspect scans, row estimates, joins, and sorting.
  3. Write down the access pattern: List the equality filters, range filters, join columns, sort order, and limit.
  4. Check existing indexes: Avoid creating duplicates or assuming a foreign key already has an index on its referencing side.
  5. Create one targeted index: Choose the simplest type and column order that matches the query.
  6. Measure again: Compare the plan and actual behavior with representative data. A planner may correctly choose a sequential scan.
  7. Review write impact: Watch storage and write performance, and remove indexes that provide no meaningful benefit after checking the workload.
For student and school management systems

When a dashboard filters grades by student, class, semester, or academic year, start by inspecting the exact query and its RLS policy. A carefully ordered composite index can help a common access pattern, but the right design depends on which filters are always present and how the data is distributed.

PostgreSQL indexes: common questions

Does PostgreSQL automatically create indexes?

PostgreSQL creates a unique B-tree index for a primary key and for a unique constraint. It does not automatically create an index on the referencing side of a foreign key. Review those columns when joins or parent-row updates and deletes are expensive.

Why is PostgreSQL not using my index?

The table may be small, the query may return many rows, the index may not match the filter operators, the leading columns may not fit the query, or planner statistics may be out of date. Inspect the plan and data distribution before forcing a different design.

Do indexes make inserts slower?

They can. PostgreSQL has to maintain relevant indexes as rows are inserted, updated, or deleted. That is why each index should support a real query or constraint and be reviewed as the application changes.

If you are still choosing a backend for a new application, read Supabase vs Firebase. If your application exposes database-backed features to users, review the website security checklist and keep RLS policies enabled and correctly tested.

← Back to Raazim Tech Insights