{"canonical_url":"https://engineer.company/glossary/query-plan/","content_markdown":"# Query plan\n\n## What it is\n\nA query plan describes the operations a database chooses to produce the result\nof a query. SQL states the result in terms of rows, joins, filters and grouping.\nThe database can realise that result through several possible strategies. A plan\ncan show a table scan, an index lookup, a join between two inputs, or a step\nthat sorts and groups records. Operations feed work to one another, so the\ndiagram or text shows both the local operation and where its input comes from.\n\nIn PostgreSQL, EXPLAIN shows the planned operations with estimated costs and row\ncounts. These are estimates in units used by the planner. EXPLAIN ANALYZE\nactually runs the statement and reports observed timing, rows and loops for the\noperations. The options available to PostgreSQL can also report buffer activity\nand other work. Compare estimates and observations to locate the first\nsurprising decision. An inaccurate row estimate early in the plan can affect the\njoin strategy or memory demand later.\n\nFor a query that asks for recent service tickets for a particular customer, one\npossible plan scans an index to find the small set of relevant rows. When a\ndifferent parameter covers a large share of the table, a scan over the table can\nmake better use of storage and memory. The planner chooses under assumptions\nabout the data and available operations. What works well for one customer or\ntime range can perform differently for another.\n\n## Why it matters\n\nA latency measurement shows the experience, while a plan helps explain where\ntime was spent and which change is worth testing. A missing index is one\npossible finding. Filtering after a join, unexpectedly many repetitions of a\nsearch, spilling a sort to disk and poorly estimated filters point to different\nchanges. Use the plan alongside end-to-end timing and load measurements. An\nindividual operation can be inexpensive in isolation and dominate the request\nwhen the database repeats it many times.\n\nPlans also expose performance changes after an ordinary deployment. New data\ndistributions, stale statistics and changes to parameter usage can move a\nfrequent query onto a different plan. A test with evenly distributed fixture\ndata may never exercise the expensive version seen by a large customer. Collect\nrepresentative parameter groups and compare several executions. Pay particular\nattention to queries involving skewed values, large date ranges and tables that\ngrow at different rates.\n\nThe best result depends on what the system needs to optimise. A plan that\nreturns the first screen quickly may matter more than one that produces every\npossible matching row slightly faster. A scheduled export has different needs.\nChanges such as a covering index can benefit certain reads while adding write\ncost or storage. Agree on the performance measure before changing the query or\nlayout, and record the data size, parameter set and relevant settings so\nsomebody can repeat the experiment.\n\n## What it looks like in practice\n\nStart with a slow ticket search and capture the statement and representative\nparameters without copying personal data into an incident report. Run an\nestimated plan on an environment that resembles production. Make sure a query\nyou intend to run for measurements is safe to execute there. Compare the size of\nintermediate inputs and note the order of joins and filters. On a suitable read\ntest, collect the estimated and actual rows, loops, buffer activity and elapsed\ntime, and record the response seen from the application.\n\nSuppose a customer filter is estimated to match ten tickets but actually matches\nfifty thousand. Work back from the first difference. Look at table statistics,\nselectivity for the affected customer, correlation between customer and date,\nand the form of the query. Then change one factor at a time and compare the\noutcome with a small customer as well as the large one. Check both a\nrepresentative repeat and the effect on concurrent use. Use a separate\nenvironment to investigate queries that could change data or generate\nsubstantial load.\n\nOur\n[PostgreSQL optimisation case study](/portfolio/accelerated-postgresql-performance-by-10x/)\ndescribes using EXPLAIN ANALYZE to find inefficient joins and subqueries\nalongside indexing and partitioning work. It illustrates a reason to collect\nevidence before choosing a fix. The ticket example gives a repeatable way to\ninvestigate one type of bad estimate, so readers can apply the same diagnosis to\na query whose parameters they understand.\n\n## Where it goes wrong\n\nExecuting a plan with analysis can have expensive or persistent effects. It runs\nthe statement, which can write data for a modifying query, lock resources or\ncall functions. Prefer safe read examples against representative non-production\ndata when learning the tool. If a live diagnostic is justified, bound its time\nand scope, review the specific statement and database semantics, and determine\nwhich possible effects a rollback can and cannot reverse.\n\nA plan's costs are estimates expressed in planner units. Treating them as\nmeasurements in milliseconds can lead to the wrong comparison. Actual timing can\nalso include measurement overhead and the state of caches at that moment.\nPreserve the original query, parameters, node estimates and execution data\nbefore changing resources. If the new plan appears faster, confirm that it\nremains faster across the relevant paths and under workload.\n\nA sequential scan can be an efficient choice when a query needs most of a table.\nAn index can also make a point lookup much faster when it filters to a small\nnumber of blocks. Diagnose the work and selectivity instead of assigning a fixed\njudgement to an operation name. Look for the first bad estimate or avoidable\nwork, then test whether your change improves the end-to-end request and fits the\nrest of the workload.\n\n## Further reading\n\n- [PostgreSQL on using EXPLAIN](https://www.postgresql.org/docs/18/using-explain.html)\n  explains costs, plan nodes and actual execution reporting.\n- [PostgreSQL planner statistics](https://www.postgresql.org/docs/18/planner-stats.html)\n  describes what the planner knows about row distributions.\n- [PostgreSQL EXPLAIN reference](https://www.postgresql.org/docs/18/sql-explain.html)\n  documents measurement options and which statements are executed.\n\n\u003chttps://engineer.company/glossary/query-plan/\u003e\n","date_modified":"2026-11-24T21:48:58Z","description":"How to read a query plan, compare estimates with actual work, and choose a change worth measuring.","formats":{"gemtext":"https://engineer.company/glossary/query-plan/index.gmi","gopher":"https://engineer.company/glossary/query-plan/gophermap","html":"https://engineer.company/glossary/query-plan/","json":"https://engineer.company/glossary/query-plan/index.json","markdown":"https://engineer.company/glossary/query-plan/index.md","pdf":"https://engineer.company/glossary/query-plan/index.pdf"},"kind":"page","language":"en","title":"What is a query plan?","url":"https://engineer.company/glossary/query-plan/","version":1}