Back to explore
Data engineeringDeep dive5 min

How PostgreSQL executes a query

The parser, planner, and executor behind a SQL query.

Process overview

Conceptual illustration for How PostgreSQL executes a query
  1. SQL
  2. Parse
  3. Rewrite
  4. Plan
  5. Execute

Steps

5 steps

SQL reaches the database

An application sends a SQL query over its database connection. The server receives a description of the result the application wants.

Text becomes a query tree

PostgreSQL checks syntax and transforms the query into a tree. Names and expressions gain meaning through the database’s catalog.

Rules reshape the query

The rewrite stage applies stored rules. A reference to a view can become a query against the base tables defined by that view.

The planner chooses a route

The planner considers possible access paths and estimates their costs. It selects an execution plan, which might use an index or scan a table.

The plan produces rows

The executor follows the plan, fetching rows and applying operations such as joins, filters, and sorts. The resulting rows return to the application.

Scope

The PostgreSQL query pipeline, simplified. Plan choices depend on statistics, indexes, configuration, and the actual query.

Source

PostgreSQL · The path of a query(opens in a new tab)
Saved explanations