---
title: "Query plans and query profiling"
description: "Read CoraDB query plans with the corasql ;plan command and profile execution with SET TRACE ON and SHOW TRACE, including MATCH."
url: "https://www.coradb.ai/manual/sql/tuning_plan.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/tuning_plan.md"
product: "CoraDB"
version: "1.0"
keywords: "coradb query plan, explain plan, set optimization level, get optimization level, nested loop join, index join, merge join, query profiling, set trace on, show trace, trace json"
---

# Query plans and query profiling

## Viewing query plan

The *query plan* shows how CoraDB will execute a query: the order in which tables are read, how they are read (index or full scan) and how they are joined. There are two ways to see it:

- In corasql, the session commands `;plan simple` and `;plan detail` print the plan of each query you run. See [Session commands](https://www.coradb.ai/manual/corasql.html#session-commands).
- In any client, **SET OPTIMIZATION LEVEL** controls whether plans are printed (to the client's output, for example in corasql) and whether queries are executed at all.

```sql
SET OPTIMIZATION LEVEL level;
GET OPTIMIZATION LEVEL [ { INTO | TO } :variable ];
```

| Level | Optimizes | Prints plan | Executes |
|---|---|---|---|
| 0 | No (simplest plan; for debugging only) | no | yes |
| **1** (default) | yes | no | yes |
| 2 | yes | no | **no** |
| 257 (256 + 1) | yes | Simple plan | yes |
| 258 (256 + 2) | yes | Simple plan | **no** |
| 513 (512 + 1) | yes | Detailed plan | yes |
| 514 (512 + 2) | yes | Detailed plan | **no** |

> **Warning:**
> At levels 2, 258 and 514 *no* statement is executed: not only **SELECT**, but also **INSERT**, **UPDATE**, **DELETE**, **REPLACE**, triggers and serials. Use them to examine plans, and set level 1 again afterwards.


Add the hint `/*+ RECOMPILE */` when you look at plans, so that a cached plan is not reused.

### Reading a plan

The following query lists the customers of the 100 most recent orders (order IDs above 2800). `;plan detail`, or level 513, prints:

```sql
SET OPTIMIZATION LEVEL 513;

SELECT /*+ RECOMPILE */ DISTINCT c.company_name, o.order_date
FROM orders o INNER JOIN customer c ON o.customer_id = c.id AND o.id > 2800;
```

```text
Join graph segments (f indicates final):
seg[0]: [0]
seg[1]: order_date[0] (f)
seg[2]: customer_id[0]
seg[3]: id[0]
seg[4]: [1]
seg[5]: company_name[1] (f)
seg[6]: id[1]
Join graph nodes:
node[0]: orders o(2914/23) (sargs 1) location (idx:0, group:-1)
node[1]: customer c(1000/11) location (idx:1, group:-1)
Join graph equivalence classes:
eqclass[0]: customer_id[0] id[1]
Join graph edges:
term[0]: o.customer_id=c.id (sel 0.001) (join term) (mergeable) (inner-join) (indexable customer_id[0] id[1]) location (idx:0, group:-1)
Join graph terms:
term[1]: o.id range (2800 gt_inf max) (sel 0.1) (rank 2) (sarg term) (not-join eligible) (indexable id[0]) location (idx:0, group:-1)

Query plan:

temp(distinct)
    subplan: idx-join (inner join)
                 outer: iscan
                            class: o node[0]
                            index: pk_orders_id term[1]
                            cost:  5 card 291
                 inner: iscan
                            class: c node[1]
                            index: pk_customer_id term[0]
                            cost:  3 card 1000
                 cost:  10 card 291
    cost:  16 card 291

Query stmt:

select distinct c.company_name, o.order_date from orders o, customer c where o.customer_id=c.id and (o.id> ?:0 )
```

The plan is read from the inside out:

1. **outer: iscan** reads `orders` (node[0]) with the index `pk_orders_id`, limited by term[1], `o.id > 2800`.
2. For each order, **inner: iscan** looks up the customer (node[1]) in `pk_customer_id` using the join condition term[0], `o.customer_id = c.id`. Together these two steps are an **idx-join**.
3. **temp(distinct)** collects the result in a temporary list and removes duplicates.

The sections above "Query plan" explain the numbers in it:

- **Join graph nodes** list the tables with their statistics: `orders o(2914/23)` means about 2,914 rows in 23 pages. `(sargs 1)` means one filter condition applies to the table.
- **Join graph edges** are join conditions, **Join graph terms** other conditions. `sel` is the estimated selectivity (share of rows that pass), `indexable` names the columns an index can be used on.
- **cost** is the estimated cost of a step including the steps below it (CPU and I/O), **card** the estimated number of rows it returns. Both are estimates based on [statistics](https://www.coradb.ai/manual/sql/tuning.html).
- **Query stmt** is the query after rewriting by the optimizer; constants are shown as `?:n`.

The *simple* plan (`;plan simple`, level 257) shows the same plan as one line per step, with the names in the last column of the following table.

**Query plan terms**

| Detailed plan | Simple plan | Meaning |
|---|---|---|
| `sscan` | Sequential scan | Full table scan, without an index. |
| `iscan` | Index scan | Scan of an index range; `(covers)` after the index name means a [covering index](https://www.coradb.ai/manual/sql/tuning_index_opt.html#covering-index): the index alone answers the query. |
| `nl-join` | Nested-loop join | For each row of the outer table, scan the inner table. |
| `idx-join` | Correlated-index join | Nested-loop join that looks up each outer row in an index of the inner table. |
| `m-join` | Merge join | Sort both inputs on the join columns and merge them. |
| `temp` | Sort | Store rows in a temporary list, for sorting (`order:`), **DISTINCT**, **GROUP BY** and similar. |
| `outer` / `inner` | | In a nested-loop join, the table read first (outer) and the table read for each of its rows (inner). |
| `sargs` | | Conditions applied as data filters (not through an index). |
| `(inner join)`, `(left outer join)`, `(cross join)` | | Join type. A **RIGHT OUTER JOIN** may be shown as a left outer join with the tables swapped. |

### Join methods

**Merge join.** The optimizer considers sort-merge joins only with the hint **USE_MERGE** or when the system parameter [optimizer_enable_merge_join](https://www.coradb.ai/manual/admin/config_other.html#optimizer_enable_merge_join) is `yes`. Merge joins are rarely faster than index joins:

```sql
SELECT /*+ RECOMPILE USE_MERGE */ c.company_name, o.order_date
FROM customer c LEFT OUTER JOIN orders o ON c.id = o.customer_id AND o.shipping_cost > 45;
```

```text
Query plan:

temp
    order: UNORDERED
    subplan: m-join (left outer join)
                 edge:  term[0]
                 outer: temp
                            order: id[0]
                            subplan: sscan
                                         class: c node[0]
                                         cost:  14 card 1000
                            cost:  47 card 1000
                 inner: temp
                            order: customer_id[1]
                            subplan: sscan
                                         class: o node[1]
                                         sargs: term[1]
                                         cost:  30 card 291
                            cost:  43 card 291
                 cost:  272 card 1000
    cost:  281 card 1000
```

Both tables are scanned, sorted on the join columns (`order: id[0]`, `order: customer_id[1]`) and merged; the cost (281) is much higher than an index join would be.

**Join order.** If you know that one table yields far fewer rows than the other, the hint **ORDERED** makes the tables be joined in the order of the **FROM** clause, the first being the outer table:

```sql
SELECT /*+ RECOMPILE ORDERED */ p.name, oi.quantity
FROM order_items oi, product p
WHERE p.id = oi.product_id AND oi.quantity > 4;
```

```text
Query plan:

idx-join (inner join)
    outer: sscan
               class: oi node[0]
               sargs: term[1]
               cost:  50 card 1123
    inner: iscan
               class: p node[1]
               index: pk_product_id term[0]
               cost:  3 card 2115
    cost:  77 card 1123
```

More hints are described in [SQL and index hints](https://www.coradb.ai/manual/sql/tuning_hints.html).


## Query profiling

A plan shows what the optimizer *expects*. To see what actually happened when a query ran (time, pages fetched, rows read at each step), turn on SQL tracing:

```sql
SET TRACE { ON | OFF } [ OUTPUT { TEXT | JSON } ];
SHOW TRACE;
```

- **SET TRACE ON** traces the following queries of the session; **OUTPUT TEXT** is the default.
- **SHOW TRACE** returns the trace of the last query as a string. If that query had the hint `/*+ RECOMPILE */`, the trace also contains its plan.
- In corasql, `;trace on` shows the trace automatically after each query; see [Set SQL trace](https://www.coradb.ai/manual/corasql.html#set-autotrace).
- Tracing is not available in stand-alone corasql (`-S`), and batched or array executions are not traced.

The following query finds the customers with the most orders whose shipping cost was above 40:

```sql
SET TRACE ON;

SELECT /*+ RECOMPILE */ c.company_name, COUNT(*) AS orders, SUM(o.shipping_cost) AS shipping
FROM customer c, orders o
WHERE c.id = o.customer_id AND o.shipping_cost > 40
GROUP BY c.company_name
ORDER BY 2 DESC, 1
LIMIT 3;

SHOW TRACE;
```

```text
Query Plan:
  SORT (order by)
    SORT (group by)
      NESTED LOOPS (inner join)
        TABLE SCAN (c)
        INDEX SCAN (o.fk_orders_customer_id) (key range: c.id=o.customer_id)

  rewritten query: select c.company_name, count(*), sum(o.shipping_cost) from customer c, orders o where c.id=o.customer_id and (o.shipping_cost> ?:0 ) group by c.company_name order by 2 desc , 1 for orderby_num()<= ?:1

Trace Statistics:
  SELECT (time: 3, fetch: 5924, ioread: 0)
    SCAN (table: customer), (heap time: 0, fetch: 1011, ioread: 0, readrows: 1000, rows: 1000)
      SCAN (index: orders.fk_orders_customer_id), (btree time: 2, fetch: 4912, ioread: 0, readkeys: 650, filteredkeys: 0, rows: 2910) (lookup time: 1, rows: 86)
    GROUPBY (time: 0, hash: true, sort: false, rows: 80)
    ORDERBY (time: 0, sort: true, page: 0, ioread: 0)
```

How to read it:

- **SELECT**: the whole query took 3 ms and 5,924 page fetches, without disk reads (all pages were in the buffer). Running the query again usually shows fewer reads.
- **SCAN (table: customer)**: all 1,000 customers were read from the heap.
- **SCAN (index: orders.fk_orders_customer_id)**: for each customer, the foreign key index on `orders.customer_id` was searched: 650 distinct keys, 2,910 index entries. Fetching the rows and applying `o.shipping_cost > 40` (*lookup*) left 86 rows.
- **GROUPBY**: 86 rows were aggregated by hashing into 80 groups, without sorting. **ORDERBY** sorted them for the **LIMIT**.

Times are in milliseconds and rounded; a time below 1 ms is shown as 0. `fetch` counts page accesses, not distinct pages.

### Trace items

**SELECT**

| Item | Meaning |
|---|---|
| time | Total time of the query (ms) |
| fetch | Total page fetches |
| ioread | Total pages read from disk |

**SCAN**

| Item | Meaning |
|---|---|
| heap: time, fetch, ioread | Time and pages of a table scan without index |
| btree: time, fetch, ioread | Time and pages of an index scan |
| readrows | Rows read by this step |
| readkeys | Index keys read |
| filteredkeys | Keys that a key filter was applied to |
| rows | Rows returned by this step (after key filters for btree, after data filters for lookup) |
| lookup: time, rows | Fetching the rows found in the index and applying the data filter |
| temp: buildtime, time, hash | Scan of a temporary list; `hash` tells whether a hash list scan was used (see the [NO_HASH_LIST_SCAN](https://www.coradb.ai/manual/sql/tuning_hints.html#no-hash-list-scan) hint) |
| covered | The index covered the query (JSON output) |
| loose | A loose index scan was used |

**GROUPBY** and **ORDERBY**

| Item | Meaning |
|---|---|
| time | Time of the step (ms) |
| sort | Whether rows were sorted |
| hash | Whether hash aggregation was used (see the [NO_HASH_AGGREGATE](https://www.coradb.ai/manual/sql/tuning_hints.html#no-hash-aggregate) hint) |
| page | Temporary pages used for sorting, beyond the sort buffer |
| rows | Result rows |

In the plan part, **INDEX SCAN** shows the `key range` that limits the scan, and `covered` or `loose` when those optimizations apply. Subqueries appear as **SUBQUERY (correlated)** or **SUBQUERY (uncorrelated)** with their own statistics.

### JSON output

With **OUTPUT JSON** the same statistics are returned as a JSON document, which is easier to process in tools:

```sql
SET TRACE ON OUTPUT JSON;

SELECT p.name, COUNT(*)
FROM product p, order_items oi
WHERE p.id = oi.product_id AND p.id BETWEEN 1600 AND 1605
GROUP BY p.name;

SHOW TRACE;
```

```json
{
  "Trace Statistics": {
    "SELECT": {
      "time": 0,
      "fetch": 22,
      "ioread": 0,
      "SCAN": {
        "access": "index (product.pk_product_id)",
        "btree": { "time": 0, "fetch": 8, "ioread": 0, "readkeys": 6, "filteredkeys": 0, "rows": 6 },
        "lookup": { "time": 0, "rows": 6 },
        "SCAN": {
          "access": "index (order_items.fk_order_items_product_id)",
          "btree": { "time": 0, "fetch": 12, "ioread": 0, "readkeys": 6, "filteredkeys": 0, "rows": 18 },
          "covered": true
        }
      },
      "GROUPBY": { "time": 0, "hash": true, "sort": false, "rows": 6 }
    }
  }
}
```

The index on `order_items.product_id` covers the query (`"covered": true`): only the number of order lines per product is needed, so no `order_items` rows are read.


### Query profiling with graph match queries

For **MATCH** queries the trace contains a **SCAN (graph_match …)** step with graph-specific counters. The following query counts the customers who liked product 123 since 2025:

```sql
SET TRACE ON;

SELECT /*+ RECOMPILE */ COUNT(*)
FROM MATCH (cu:customer)-[l:likes]->(p:product)
WHERE p.id = 123 AND l.since >= DATETIME'2025-01-01 00:00:00';

SHOW TRACE;
```

```text
Query Plan:
  NESTED LOOPS (cross join)
    INDEX SCAN (p_product.pk_product_id) (key range: p.id= ?:1 )

  rewritten query: select count(*) from match (cu:customer), match (p:product)-[l:likes{1, 1}]->(cu:customer) where (l.since>= ?:0 ) and p.id= ?:1

Trace Statistics:
  SELECT (time: 0, fetch: 6, ioread: 0)
    SCAN (index: product.pk_product_id), (btree time: 0, fetch: 3, ioread: 0, readkeys: 1, filteredkeys: 0, rows: 1) (lookup time: 0, rows: 1)
      SCAN (graph_match time: 0, fetch: 0, ioread: 0, edge_fetches: 103, vertex_fetches: 1, qualified_edges: 15, qualified_vertices:0, readrows: 15, rows: 15)
```

The optimizer starts from the product, found through its primary key, and follows its 103 `likes` edges; 15 of them satisfy the date condition.

| Item | Meaning |
|---|---|
| time, fetch, ioread | Time (ms), page fetches and disk reads of the graph match |
| edge_fetches | Edges examined while following the pattern |
| vertex_fetches | Vertices examined |
| qualified_edges | Edges that satisfied the conditions on edges |
| qualified_vertices | Vertices that satisfied the conditions on vertices |
| readrows | Rows read by the graph match |
| rows | Rows it returned |

Many more fetched than qualified edges or vertices mean that the traversal examines elements that do not contribute to the result: add a more selective condition, or start the pattern from the more selective end.
