Database query processing (source code)

= Database query processing

<Database query processing> is the sequence that turns a <database query> into returned results. In a typical <SQL> system, it includes parsing the text, checking names and types, rewriting the query when appropriate, <database query optimization>, and executing the chosen <database query plan>. Planning chooses operations; execution actually performs storage accesses, <relational joins>, filtering and aggregation.<The Path of a Query in the PostgreSQL documentation>[Section 51.1, stages 2–5]{ref}

For a request for each customer's total order value, the engine might scan orders, group their <database tuples> by customer identifier, sum the values and return one result per customer. An alternative plan can first restrict the orders using a <database index>. The result specification alone does not prescribe which access method performs the work.

A query against a stored <database view> illustrates why processing has more than a text-to-loop step. PostgreSQL can rewrite the reference into a query on the underlying tables before planning. The executor then walks the resulting plan and obtains rows from its operations. The distinction is useful when diagnosing a slow query: excessive planning work, a poor plan, and unexpectedly expensive execution are different causes even if the same statement triggered them.<The Path of a Query in the PostgreSQL documentation>[Section 51.1, view rewriting and executor]{ref}