Blog Post

Microsoft Blog for PostgreSQL
9 MIN READ

A basic overview of query planning and execution in PostgreSQL

David_Rowley's avatar
David_Rowley
Icon for Microsoft rankMicrosoft
Nov 30, 2026

This article is part of Microsoft's Perspectives on PostgreSQL series, featuring insights from engineers, contributors, and builders working with PostgreSQL. The author this month is David Rowley, PostgreSQL Contributor and Committer, specializing in query planning and execution.
 

SQL is a declarative language, meaning you state what you want, and the database is in charge of figuring out the best way to answer your query. It often comes as a surprise to people how much work is involved in taking the SQL statement and doing the required processing and returning the answer.  Let’s talk about some of the things that go on behind the scenes. 

This post is my no means exhaustive. The idea here is to give an overview of some of the things that PostgreSQL does internally after you send your query to it. 

 

The PostgreSQL query planner

 

PostgreSQL uses a cost-based query planner. Many other database systems call this a “cost-based optimizer”, which is a term we often avoid in the PostgreSQL world, as “optimizer” implies there was something there to optimize in the first place.  "The planner", as it's most commonly named, takes the processed query after it’s been broken down into a node representation after some post-processing was done on it, and comes up with a query plan to allow the query executor to execute the given query in the most efficient way it knows how. 

 

Deciding the cheapest plan involves looking at various sets of statistics that may be available about the tables and columns being queried. 

 

Before looking at any statistics, an early stage of planning is heuristics-based. Here some transformations can occur that do things like pull up subqueries into the main query. 

 

If, for example, you were to write a query such as: 

 

SELECT * FROM (SELECT * FROM mytable) WHERE col1 = 10;

 

Then this stage would transform that into 

 

SELECT * FROM mytable WHERE col1 = 10;

 

While you might think that’s a rather silly query to write, it is effectively what could happen when VIEWs are expanded into their underlying query by the parse-analyze phase that runs just before the query planner is asked to plan the query. 

 

For more complex subqueries, these pull-ups may not be possible, but pushing down conditions from the outer query’s WHERE clause into the subquery might be possible. For example: 

 

SELECT * FROM (SELECT DISTINCT col1 FROM mytable) WHERE col1 = 10;

 

Could become: 

 

SELECT * FROM (SELECT DISTINCT col1 FROM mytable WHERE col1 = 10);

 

Which could allow much more efficient processing if you consider there could be an index defined on mytable (col1). 

 

There are various other optimizations considered at this phase. Other examples include transforming EXISTS or NOT EXISTS queries into semi-join or anti-join queries. 

 

The cost-based part

 

The decision on how to scan each table specified in the query, the join algorithm to use to join each table, and the method of implementing the DISTINCT or GROUP BY clauses are all cost-based decisions. 

 

This cost-based method of finding the cheapest plan requires that the query planner calculates, or more accurately “estimates” the execution effort required for each part of the plan. For example, the Seq Scan operator scans an entire table and applies an optional filter to remove rows that don’t match that filter.  The costing function that calculates the costs for that method of accessing the table knows exactly how that works and knows that we access pages in the table one after the other, and takes all that into account along with the number of pages in the table when calculating the cost. This costing function makes use of the global user configuaration parameter, seq_page_cost and adds this to the estimated cost of evaluating the filter clause, which most often consists of conditions from the query’s WHERE clause.  

 

The cost values are arbitrary floating point numbers that only have meaning when compared to other cost values, where lower values mean “cheaper”. The query planner stores the cost values it calculates in something we internally call “Paths”, which will be called “access paths” for this blog. These access paths always contain an estimate for the total cost, which is the cost of fetching all rows, and also a start-up cost, which is the cost incurred before the first row can be returned. They also contain something we call “path keys”, which define the order in which rows are returned from that path. 

 

The planner first creates these access paths for each of the base tables mentioned in the query. Access paths are created for any indexes that match any of the filters that can be pushed down to the scan level, and also for any indexes that produce results in an order that might be useful later in planning. Access paths with interesting orders will have path keys set as the planner may be able to make use of access paths with certain path keys later in planning.  All of these access paths are stored in a list in an object that’s internally dedicated to store metadata about the table being queried. Inferior access paths are removed from this list to save effort later when performing the join search. Here "inferior" does not just mean access paths which are more expensive, it can also mean ones that are similarly as expensive, but maybe don't have a defined sort order, or provide sorted output by fewer of the required sort keys. 

 

Planning joins

 

Depending on who you ask, PostgreSQL supports 3 algorithms for joining two tables together. The Nested Loop join effectively does have 3 variants, so some people might consider that 5 algorithms. The other two algorithms are Hash Join and Merge Join. The variants of Nested Loop are parameterized Nested Loops and parameterized Nested Loops with Memoize most-recently-used (MRU) caching, and also non-parameterized Nested Loops. 

 

If you have 3 tables to join: “a”, “b” and “c”, then PostgreSQL considers all legal orders of joining those tables together two at a time.  For example, it will calculate the costs to join “a” to “b”, then “a, b” to “c”, and also “a” to “c” then “a, c” to “b”, then consider the swapped join order of each, i.e. “b” to “a”, then “c” to “b, a”, etc. The planner must also consider which orders are legal, as certain relations may need to be joined first before outer-joined tables can be joined to those. You might imagine that if you add a few more tables to the query, the number of combinations to consider grows large quickly. 

 

This join search is often the most expensive part of query planning due to the sheer number of access paths which are considered. The aggressive pruning of inferior paths helps reduce the number of paths that need to be considered later.  When the search space is too large, PostgreSQL does resort to pairing tables up using a genetic algorithm (check the documentation for GEQO). We won’t discuss the details of that here. 

 

After the cheapest join order is found

 

It’s now time to create access paths for any DISTINCT / GROUP  BY / ORDER BY clauses. The SQL standard defines that semantically, DISTINCT is always applied before GROUP BY and GROUP BY before ORDER BY. So the first step is to create access paths if the query has a DISTINCT clause. The two methods considered for that are “Hash Aggregate” and “Unique”. Hash Aggregate can take input rows in any order, so if the underlying access-path which the DISTINCT is built upon is a Seq Scan, or a Hash Join, each of which has no defined output order, then Hash Aggregate may be preferable, otherwise a Sort would be required before the Unique node, as Unique requires presorted input rows. In any case, the code to do this will consider sorting the cheapest access path, alongside using any access path which provides pre-sorted input. In some cases it may be cheaper to perform a Sort on an unsorted access path than it is to use an Index which provides pre-sorted results.  PostgreSQL also considers access paths which are only sorted by a subset of the required leading sort keys.  In this case, the planner may be able to use Incremental Sort to fully sort the partially sorted input. 

 

GROUP BY is costed in a similar way, but builds upon the output paths of the DISTINCT access paths, if relevant. Group Aggregate takes the place of Unique nodes for this. ORDER BY can only either use pre-sorted access paths, or sort the cheapest available access path, or try an incremental sort of some path that is only partially presorted (as defined by the access path’s path keys) in the required output order. 

 

The planner then goes on to build the final plan. Remember that at each stage we calculated the total cost and startup path of each access path, so the final plan can still depend on the context where the plan is being executed. For example, a CURSOR statement may prefer a plan that’s fast to get the first row rather than a plan that has the cheapest total cost. 

 

The planner also considers “partial access paths” at most stages.  These are for allowing parallel queries. To keep things simple, that’s not discussed here. 

 

Query Execution

 

The final plan produced by the query planner is picked up by the query executor. The final plan is a tree-shaped structure and contains various extra information which the executor uses. For example, a Sort node needs to know which sort operators to use and which columns to sort on. A Hash Join needs to know which column(s) to key the hash table on. 

 

The executor conceptually has 3 stages: start-up, run, and shutdown. The start-up phase allocates all the state required for execution and builds another tree structure containing those states. The “Run” phase requires that the “run” function is invoked for the root plan node, normally until it returns NULL to indicate that no more rows exist. Each intermediate node then executes its own run function until the leaf nodes are reached. The leaf nodes are things like Seq Scan or Index Scan, and the intermediate nodes are just there to manipulate those rows or the order of those rows. When the scan nodes run out of rows, it effectively return NULL to indicate “no more rows exist” to the calling node. What happens then depends on the node type. The Sort node, for example, then knows that all rows have been read and it can then perform the sort and return the first row from the sorted results. When the root node returns NULL, no more tuples exist, and the plan can be shut down to clean up memory and any temporary files used during execution. 

 

Let’s say you have a query such as: 

 

SELECT * FROM mytable ORDER BY col1;

 

And say the planner decided that a Seq Scan on “mytable” with a Sort node below it was the cheapest way to execute the query. In this case, Sort would be the root node and the Seq Scan node would be the direct child of Sort. The Sort node would be executed, and that would in turn call the run function on the Seq Scan node and store the resulting row, then repeat until Seq Scan returns NULL to indicate “no more rows”. At that point, the physical sort operation would be performed, and the first row of the sorted results would be returned. When the root node is executed for the 2nd time, the Sort node’s state indicates the sort is already done, so it knows all the rows are stored and sorted and that it’s ready to return the next sorted row, or NULL, if there are no more rows. 

 

Greedy vs Non-greedy nodes 

As mentioned above with the Sort node, some nodes need to read all rows from their sub node before they can return a single row. Sort is an example of a greedy node as it must read all input rows and sort them before it can output any row. Nodes like Seq Scan can simply return rows as soon as they find a row to return. Another example of a greedy node is Hash Join, where the Hash Join’s inner sub node must be exhausted (the side that is hashed) before the other side (the probe side) is executed. 

 

Nodes which use memory

Several node types require storing rows before they’re able to return any rows. The memory to store tuples is allocated by the node itself, and the memory limits imposed to avoid too much memory being allocated are controlled by work_mem, or work_mem * hash_mem_multiplier for node types that build hash tables, such as Hash Join and Memoize. 

 

Closing 

Understanding what's been described above can be helpful to debug slow queries. Once you understand that query plans are executed from the root node of the plan and that each node requests rows from its sub node(s), the EXPLAIN command becomes easier to understand. The documentation also has a section on the query planner. There is also the README which explains various concepts, also if you feel so inclined, you could also view the C code with that link.

About Perspectives on PostgreSQL. 

Perspectives of PostgreSQL is a monthly blog series featuring insights from Microsoft engineers, contributors, and builders working with PostgreSQL. Explore more articles on the Microsoft for PostgreSQL blog.

 

Published Nov 30, 2026
Version 1.0
No CommentsBe the first to comment