> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Find and fix a full table scan

> Spot a query that reads the whole table, read the plan and the index recommendation, and add the secondary index that makes it read only the rows it returns.

> [!NOTE]
>
> **Recipe** · 15 minutes · **Works on:** Cockroach Continuum, CockroachDB Cloud, self-hosted · **Verified on:** CockroachDB v26.4.1, Dec 1, 2026

## What you'll fix

A "latest orders for this customer" query that gets slower as the table grows. The plan shows a `FULL SCAN`: to return 10 rows, CockroachDB reads all 100,000. You'll find the query, read its plan, and add one secondary index so the same query reads 10 rows.

Full table scans are the most common reason a query that was fast in development is slow in production. They also make [transaction contention](https://docs.cockroachlabs.com/docs/cookbook/transaction-contention.md) worse, because a query that reads more rows conflicts with more writes.

## Start a cluster

> [tab] Cockroach Continuum
>
> Create a free cluster by following the [Continuum quickstart](https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart.md), then open a SQL shell with the connection string from the Console.

> [tab] Local (self-hosted)
>
> [Install CockroachDB](https://docs.cockroachlabs.com/docs/stable/install-cockroachdb-mac.md), then start a temporary in-memory cluster with a SQL shell:
>
> ```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> cockroach demo --no-example-database
> ```

## Create the problem

An `orders` table keyed by a random UUID, with 100,000 rows across 5,000 customers:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE orders (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  customer_id INT NOT NULL,
  status STRING NOT NULL,
  total DECIMAL(10,2) NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

INSERT INTO orders (customer_id, status, total)
SELECT (i % 5000) + 1,
       CASE WHEN i % 10 = 0 THEN 'open' ELSE 'shipped' END,
       (i % 200) + 0.99
FROM generate_series(1, 100000) AS g(i);

ANALYZE orders;
```

The application asks for one customer's 10 most recent orders:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT id, status, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;
```

## Find it

**Read the plan.** Put [`EXPLAIN`](https://docs.cockroachlabs.com/docs/stable/explain) in front of the query:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
EXPLAIN SELECT id, status, total FROM orders
WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10;
```

```
• top-k
│ order: -created_at
│ k: 10
│
└── • filter
    │ filter: customer_id = 42
    │
    └── • scan
          estimated row count: 100,000 (100% of the table; stats collected 0 seconds ago)
          table: orders@orders_pkey
          spans: FULL SCAN

index recommendations: 1
1. type: index creation
   SQL command: CREATE INDEX ON defaultdb.public.orders (customer_id, created_at DESC) STORING (status, total);
```

Three things to read: `spans: FULL SCAN` on the primary index, `100% of the table`, and an index recommendation from the optimizer.

**Find it across the workload.** You usually don't know which query is the problem. [`SHOW FULL TABLE SCANS`](https://docs.cockroachlabs.com/docs/stable/show-full-table-scans) lists the statement fingerprints whose plans used a full scan. Run the query itself at least once first: `EXPLAIN` doesn't count, and a statement appears in the list about a second after it runs.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT query, count, rows_read_avg
FROM [SHOW FULL TABLE SCANS]
WHERE query LIKE '%orders%';
```

```
query: SELECT id, status, total FROM orders WHERE customer_id = _ ORDER BY created_at DESC LIMIT _
count: 1
rows_read_avg: 100000
```

In the Console, the same queries appear on the **Insights** page as **Suboptimal plan** insights, with the index recommendation attached: the [Cloud Console Insights page](https://docs.cockroachlabs.com/docs/cockroachcloud/insights-page.md) or the [DB Console Insights page](https://docs.cockroachlabs.com/docs/stable/ui-insights-page.md) for self-hosted clusters.

## Fix it

Create the index the optimizer recommended. It matches the query: the filter column first, then the sort column, with the returned columns stored so the query never goes back to the primary index.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE INDEX orders_customer_created_idx
  ON orders (customer_id, created_at DESC)
  STORING (status, total);
```

Because `created_at` is in the key, the rows are already in order and the query can stop after 10. Always read a recommendation before applying it: it covers the one query, not the write cost to the rest of your workload.

Run [`EXPLAIN ANALYZE`](https://docs.cockroachlabs.com/docs/stable/explain-analyze) to compare what actually happened:

| | Before | After |
| - | - | - |
| Index used | `orders@orders_pkey` | `orders@orders_customer_created_idx` |
| Spans | `FULL SCAN` | `[/42 - /42]` |
| Rows decoded from KV | 100,000 | 10 |

`CREATE INDEX` runs online. Reads and writes continue while the index is built in the background.

## How it fails

| Situation | What happens | What to do |
| - | - | - |
| The table is small, or the query returns most of it | The optimizer may still choose a full scan, because it is cheaper | Nothing. Not every full scan is a problem. Look at `rows_read_avg` against rows returned |
| Statistics are stale after a large load | Estimates are wrong and the plan may not use the new index | Run `ANALYZE <table>`, or wait for automatic statistics collection |
| The query filters on an expression, such as `lower(email)` | An index on the plain column can't be used | Index the expression, or a [computed column](https://docs.cockroachlabs.com/docs/stable/computed-columns.md) |
| You build an index on a large, busy table | The backfill adds load while it runs | Build it outside your peak, and watch the job on the **Jobs** page |

## Trade-offs and when not to use it

* **Every index costs writes.** Each `INSERT`, `UPDATE`, and `DELETE` also writes to every secondary index. Check for indexes nothing reads with the **Schema Insights** tab, or with [`information_schema.crdb_index_usage_statistics`](https://docs.cockroachlabs.com/docs/stable/information-schema#crdb_index_usage_statistics), and drop them.
* **`STORING` trades storage for reads.** Stored columns are copied into the index. Store only what the query returns.
* **Sequential keys can create a hotspot.** An index whose leading column only grows, such as a timestamp, sends all new writes to one range. Lead with a column that spreads out, or use a [hash-sharded index](https://docs.cockroachlabs.com/docs/stable/hash-sharded-indexes.md). See [Understand hotspots](https://docs.cockroachlabs.com/docs/stable/understand-hotspots.md).

> [!NOTE]
>
> **On Cockroach Continuum with Cockroach Aegis (private preview):** Aegis watches the workload and proposes index recommendations with their expected effect. See [Review and apply an index recommendation](https://docs.cockroachlabs.com/docs/continuum/aegis-example-workflows.md#review-and-apply-an-index-recommendation).

## Give it to your agent

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
Find full table scans on this CockroachDB cluster and fix the worst one. Run
SHOW FULL TABLE SCANS and sort by rows_read_avg. For the top query, run EXPLAIN
and read the spans and any index recommendation. Propose one CREATE INDEX whose
key is the filter columns then the sort columns, with STORING for the returned
columns. Confirm with EXPLAIN ANALYZE that rows decoded dropped, and name the
write cost of the new index before applying it.
Reference: https://docs.cockroachlabs.com/docs/cookbook/fix-full-table-scans
```

## Go deeper

* [Secondary indexes](https://docs.cockroachlabs.com/docs/stable/schema-design-indexes.md) and [index best practices](https://docs.cockroachlabs.com/docs/stable/schema-design-indexes.md#best-practices)
* [`EXPLAIN`](https://docs.cockroachlabs.com/docs/stable/explain) and [`EXPLAIN ANALYZE`](https://docs.cockroachlabs.com/docs/stable/explain-analyze)
* [Statement tuning with `EXPLAIN`](https://docs.cockroachlabs.com/docs/stable/sql-tuning-with-explain)
* [Performance Tuning Recipes](https://docs.cockroachlabs.com/docs/stable/performance-recipes.md), where this recipe came from

> [card] [Practice query tuning in Cockroach University](https://learn.cockroachlabs.com/?utm_source=docs\&utm_medium=recipe\&utm_content=fix-full-table-scans)
>
> Free developer path with hands-on browser labs.
