Files
Miranda Limonczenko fca0f99354 docs: move the explain() guide to guides/api/query-plans (#52471)
Closes DOCS-1496

## Problem

The Debugging performance issues page is moved to the Data API as a part
of the Information Architecture plan laid out in Option 1 of the [Docs
navigation architecture
proposal](https://app.notion.com/p/supabase/Q4-2027-Proposal-Docs-navigation-architecture-3f25004b775f81f49dbad710a732ef61).

The [docs tree
tests](https://github.com/supabase/evals/tree/docs/ia-tree-tests/evals/docs-tree-tests)
in supabase/evals drove the rename. Each test gives an agent a developer
goal and only the navigation labels, with no page content and no search.

- **The task:** [one
test](https://github.com/supabase/evals/tree/docs/ia-tree-tests/evals/docs-tree-tests/investigate-tree-036-client-call-execution-plan)
asks how to see the plan Postgres uses for a slow supabase-js
`.from('orders').select()` call. Its answer is this page.
- **Today's label:** the page sits under Database as "Debugging
performance issues". That label names a symptom many pages share, not
the tool the page teaches.
- **The change:** round 4 of the tests split the `explain()` content
into its own topic, labeled "Query plans with explain()" and placed in
Data API, Tools, next to the other client tools. Option 1 fixed every
task its new topics targeted.
- **Why the whole page moves:** `explain()` is the only thing the page
covers, so a split would leave an empty source. The page takes the
topic's label as its title.

## Solution

- **Move, not split:** the whole page covers `explain()`, so a split
would leave an empty source. The page moves to `guides/api/query-plans`,
and the old URL redirects there. The existing
`api/rest/debugging-performance` redirect now points straight to the new
URL, so there's no chain.
- **Anchors:** the four H2s keep their anchors, so the client reference
link to `#enabling-explain` resolves through the redirect. The two H3s,
Example data and Expected response, are gone. Nothing links to them.
- **Navigation:** both entries in today's navigation point to the new
URL, with the label "Query plans with explain()". In Option 1, the Data
API, Tools entry points to the new page, and the Database entry is gone,
since it would list the page twice. This was the last Option 1 topic
that linked to a section of its source page, so the test that tracked
those topics is removed.
- **Inbound link:** Realtime reports links to the new URL.
- **Cross-links:** the page links Query Performance for finding slow
queries, Query optimization for plans of SQL you run yourself, Row Level
Security performance for slow policies, and the `explain()` client
reference. Query optimization and Row Level Security performance link
back to it.
- **Guide shape:** a value-statement opener with the reason `explain()`
is off by default, and the sample table before the query that reads it.
The SQL samples have no comments, and the `format` option has an
example. Production readers are told to set up the filter before
enabling, and the options paragraph warns that `analyze` on a write
changes data.
- **Row Level Security performance:** the caution about restricting
plans now sits above the step that enables them.
- **Sample fix:** `pgrst.db_pre_request` holds one function, so the
production step now checks for an existing one and says to call the
filter from it. The disable step clears the pre-request setting only for
readers who set the filter directly. The filter function sets
`search_path`, so the Security Advisor doesn't flag it. It matches the
`Accept` header case-insensitively anywhere in the list, because
PostgREST accepts `Application/vnd.pgrst.plan+text` and the old prefix
check let it through. The check for an existing pre-request function
reads `pg_db_role_setting`, which also shows per-database settings that
`pg_roles.rolconfig` leaves out. When both a global and a per-database
setting exist, the page says PostgREST uses the per-database one. The
function is created and set as `public.filter_plan_requests`, because
PostgREST resolves an unqualified name against the requested schema
first. After the filter, the page says the Supabase Platform sets
`cf-connecting-ip`, and that a self-hosted project needs a header its
proxy overwrites.

### Verification

`test-the-docs`, local stack, Supabase CLI v2.39.2. Each SQL fence ran
in document order. The `supabase-js` calls were checked through the HTTP
request they send, with `Accept: application/vnd.pgrst.plan`.

| Step | Result |
| --- | --- |
| Plan request before enabling | 406, as expected |
| Enable, then request a plan | 200, text plan, and JSON with `+json` |
| Sample table, no extra grant | readable by `anon` |
| Pre-request filter with `set search_path = ''`, non-matching IP | 401
`Not allowed to use application/vnd.pgrst.plan`, normal requests 200 |
| Filter, mixed-case `Application/vnd.pgrst.plan+text` | old filter 200
with a plan, new filter 401; matching IP 200 |
| Insert plan with `options=analyze` | row persists after the request;
without `analyze`, no row |
| Existing-function check with an `in database` setting |
`pg_db_role_setting` shows it, `rolconfig` doesn't |
| Disable | plan requests 406, normal requests 200 |
| `cf-connecting-ip` on a hosted project | checked in review on a test
project: Cloudflare sets it, and a request that sends its own value is
rejected at the edge with `error code: 1000` |

### Not verified

- **Deferred:** the TypeScript fences, because the sandbox runs Node
only for example apps. The plan values in the example response come from
the old page and differ slightly from a local run.
- **Old links left on the redirect:** the client reference specs
(`supabase_{dart,py,kt,swift}`), the supabase-js doc comment, and one
`www` blog post still link to the old URL.

## Manual testing

1. Open [Query plans with
explain()](https://docs-git-docs-query-plans-supabase.vercel.app/docs/guides/api/query-plans).
See the enable, use, production, and disable sections.
2. Open [the old
URL](https://docs-git-docs-query-plans-supabase.vercel.app/docs/guides/database/debugging-performance#enabling-explain).
See it redirect to the new page at Enabling `explain()`.
3. In the Database sidebar under Debugging, click **Query plans with
explain()**. See the new page open.
2026-11-02 10:47:06 -08:00

127 lines
5.3 KiB
Plaintext

---
title: 'Query Optimization'
description: 'Choosing indexes to improve your query performance.'
subtitle: 'Choosing indexes to improve your query performance.'
footerHelpType: 'postgres'
---
When working with Postgres, or any relational database, indexing is key to improving query performance. Aligning indexes with common query patterns can speed up data retrieval by an order of magnitude.
This guide is intended to:
- help identify parts of a query that have the potential to be improved by indexes
- introduce tooling to help identify useful indexes
This is not a comprehensive resource, but rather a helpful starting point for your optimization journey.
If you're new to query optimization, you may be interested in [`index_advisor`](/docs/guides/database/extensions/index_advisor), our tool for automatically detecting indexes that improve performance on a given query.
## Example query
Consider the following example query that retrieves customer names and purchase dates from two tables:
```sql
select
a.name,
b.date_of_purchase
from
customers as a
join orders as b on a.id = b.customer_id
where a.sign_up_date > '2023-01-01' and b.status = 'shipped'
order by b.date_of_purchase
limit 10;
```
In this query, there are several parts that indexes could likely help in optimizing the performance:
### `where` clause:
The `where` clause filters rows based on certain conditions, and indexing the columns involved can improve this process:
- `a.sign_up_date`: If filtering by `sign_up_date` is common, indexing this column can speed up the query.
- `b.status`: Indexing the status may be beneficial if the column has diverse values.
```sql
create index idx_customers_sign_up_date on customers (sign_up_date);
create index idx_orders_status on orders (status);
```
### `join` columns
Indexes on the columns used for joining tables can help Postgres avoid scanning tables in their entirety when connecting tables.
- Indexing `a.id` and `b.customer_id` would likely improve the performance of the join in this query.
- Note that if `a.id` is the primary key of the `customers` table it is already indexed
```sql
create index idx_orders_customer_id on orders (customer_id);
```
### `order by` clause
Sorting can also be optimized by indexing:
- An index on `b.date_of_purchase` can improve the sorting process, and is particularly beneficial when a subset of rows is being returned with a `limit` clause.
```sql
create index idx_orders_date_of_purchase on orders (date_of_purchase);
```
## Key concepts
Here are some concepts and tools to keep in mind to help you identify the best index for the job, and measure the impact that your index had:
### Analyze the query plan
Use the `explain` command to [understand the query's execution](/kb/troubleshooting/understanding-postgresql-explain-output-Un9dqX). Look for slow parts, such as Sequential Scans or high cost numbers. If creating an index does not reduce the cost of the query plan, remove it.
For example:
```sql
explain select * from customers where sign_up_date > 25;
```
To get the plan of a Data API request from a client, see [Query plans with explain()](/docs/guides/api/query-plans).
### Use appropriate index types
Postgres offers various index types like [B-tree, Hash, GIN, etc](https://www.postgresql.org/docs/current/indexes-types.html). Select the type that best suits your data and query pattern. Using the right index type can make a significant difference. For example, using a BRIN index on a field that always increases and lives within a table that updates infrequently - like `created_at` on an `orders` table - routinely results in indexes that are +10x smaller than the equivalent default B-tree index. That translates into better scalability.
```sql
create index idx_orders_created_at ON customers using brin(created_at);
```
### Partial indexes
For queries that frequently target a subset of data, a partial index could be faster and smaller than indexing the entire column. A partial index contains a `where` clause to filter the values included in the index. Note that a query's `where` clause must match the index for it to be used.
```sql
create index idx_orders_status on orders (status)
where status = 'shipped';
```
### Composite indexes
If filtering or joining on multiple columns, a composite index prevents Postgres from referring to multiple indexes when identifying the relevant rows.
```sql
create index idx_customers_sign_up_date_priority on customers (sign_up_date, priority);
```
### Over-Indexing
Avoid the urge to index columns you operate on infrequently. While indexes can speed up reads, they also slow down writes, so it's important to balance those factors when making indexing decisions.
### Statistics
Postgres maintains a set of statistics about the contents of your tables. Those statistics are used by the query planner to decide when it's is more efficient to use an index vs scanning the entire table. If the collected statistics drift too far from reality, the query planner may make poor decisions. To avoid this risk, you can periodically `analyze` tables.
```sql
analyze customers;
```
---
By following this guide, you'll be able to discern where indexes can optimize queries and enhance your Postgres performance. Remember that each database is unique, so always consider the specific context and use case of your queries.