50.1. The Path of a Query#
Here we give a short overview of the stages a query has to pass to obtain a result.
A connection from an application program to thePostgres Pro server has to be established. The application program transmits a query to the server and waits to receive the results sent back by the server.
Theparser stage checks the query transmitted by the application program for correct syntax and creates aquery tree.
Therewrite system takes the query tree created by the parser stage and looks for anyrules (stored in thesystem catalogs) to apply to the query tree. It performs the transformations given in therule bodies.
One application of the rewrite system is in the realization ofviews. Whenever a query against a view (i.e., avirtual table) is made, the rewrite system rewrites the user's query to a query that accesses thebase tables given in theview definition instead.
Theplanner/optimizer takes the (rewritten) query tree and creates aquery plan that will be the input to theexecutor.
It does so by first creating all possiblepaths leading to the same result. For example if there is an index on a relation to be scanned, there are two paths for the scan. One possibility is a simple sequential scan and the other possibility is to use the index. Next the cost for the execution of each path is estimated and the cheapest path is chosen. The cheapest path is expanded into a complete plan that the executor can use.
The executor recursively steps through theplan tree and retrieves rows in the way represented by the plan. The executor makes use of thestorage system while scanning relations, performssorts andjoins, evaluatesqualifications and finally hands back the rows derived.
In the following sections we will cover each of the above listed items in more detail to give a better understanding ofPostgres Pro's internal control and data structures.