2 51.1. The Path of a Query #
4 Here we give a short overview of the stages a query has to pass to
6 1. A connection from an application program to the PostgreSQL server
7 has to be established. The application program transmits a query to
8 the server and waits to receive the results sent back by the
10 2. The parser stage checks the query transmitted by the application
11 program for correct syntax and creates a query tree.
12 3. The rewrite system takes the query tree created by the parser stage
13 and looks for any rules (stored in the system catalogs) to apply to
14 the query tree. It performs the transformations given in the rule
16 One application of the rewrite system is in the realization of
17 views. Whenever a query against a view (i.e., a virtual table) is
18 made, the rewrite system rewrites the user's query to a query that
19 accesses the base tables given in the view definition instead.
20 4. The planner/optimizer takes the (rewritten) query tree and creates
21 a query plan that will be the input to the executor.
22 It does so by first creating all possible paths leading to the same
23 result. For example if there is an index on a relation to be
24 scanned, there are two paths for the scan. One possibility is a
25 simple sequential scan and the other possibility is to use the
26 index. Next the cost for the execution of each path is estimated
27 and the cheapest path is chosen. The cheapest path is expanded into
28 a complete plan that the executor can use.
29 5. The executor recursively steps through the plan tree and retrieves
30 rows in the way represented by the plan. The executor makes use of
31 the storage system while scanning relations, performs sorts and
32 joins, evaluates qualifications and finally hands back the rows
35 In the following sections we will cover each of the above listed items
36 in more detail to give a better understanding of PostgreSQL's internal
37 control and data structures.