|
| 1 | +--- |
| 2 | +icon: material/help |
| 3 | +--- |
| 4 | + |
| 5 | +# EXPLAIN command |
| 6 | + |
| 7 | +`EXPLAIN` is a command that produces the query plan Postgres will use to execute a query. This allows you to check that the query is optimal, before running it. |
| 8 | + |
| 9 | +PgDog can annotate the query plan returned by Postgres with its own routing decision. This allows you to check which shard(s) the query will be sent to, and if it will be sent to the primary or a replica. |
| 10 | + |
| 11 | +### How it works |
| 12 | + |
| 13 | +To avoid breaking existing tooling which relies on the standard `EXPLAIN` format, PgDog's `EXPLAIN` is disabled by default and can be turned on with configuration: |
| 14 | + |
| 15 | +```toml |
| 16 | +[general] |
| 17 | +expanded_explain = true |
| 18 | +``` |
| 19 | + |
| 20 | +When configured, all `EXPLAIN` queries will start returning two query plans: one for Postgres and one for PgDog. For example: |
| 21 | + |
| 22 | +=== "Query" |
| 23 | + ```postgresql |
| 24 | + EXPLAIN SELECT * FROM users WHERE id = 1; |
| 25 | + ``` |
| 26 | + |
| 27 | +=== "Plan" |
| 28 | + ``` |
| 29 | + QUERY PLAN |
| 30 | + ----------------------------------------------------------------------------- |
| 31 | + Index Scan using users_pkey on sharded (cost=0.15..8.17 rows=1 width=40) |
| 32 | + Index Cond: (id = 1) |
| 33 | + |
| 34 | + PgDog Routing: |
| 35 | + Summary: shard=0 role=replica |
| 36 | + Shard 0: matched sharding key users.id using constant |
| 37 | + (6 rows) |
| 38 | + ``` |
| 39 | + |
| 40 | +#### Query plan |
| 41 | + |
| 42 | +PgDog's query plan contains the following information: |
| 43 | + |
| 44 | +| Name | Description | |
| 45 | +|-|-| |
| 46 | +| `shard` | The shard number(s) where the query will be sent. | |
| 47 | +| `role` | Whether the query will go to a replica or the primary. | |
| 48 | + |
| 49 | +For each shard, an additional note will be returned, explaining the decision to |
| 50 | +include it in the query plan. For cross-shard queries, a note will indicate why the query has to be sent to all shards, for example: |
| 51 | + |
| 52 | +=== "Query" |
| 53 | + ```postgresql |
| 54 | + EXPLAIN SELECT * FROM users; |
| 55 | + ``` |
| 56 | +=== "Plan" |
| 57 | + ``` |
| 58 | + QUERY PLAN |
| 59 | + ------------------------------------------------------------ |
| 60 | + Seq Scan on sharded (cost=0.00..22.00 rows=1200 width=40) |
| 61 | + Seq Scan on sharded (cost=0.00..22.00 rows=1200 width=40) |
| 62 | + |
| 63 | + PgDog Routing: |
| 64 | + Summary: shard=all role=replica |
| 65 | + Note: no sharding key matched; broadcasting |
| 66 | + (6 rows) |
| 67 | + ``` |
0 commit comments