OSDN Git Service

Revert sentence removal from nickname in FAQ.
[pg-rex/syncrep.git] / src / backend / optimizer / README
1 $PostgreSQL: pgsql/src/backend/optimizer/README,v 1.44 2008/04/09 00:55:30 momjian Exp $
2
3 Optimizer
4 =========
5
6 These directories take the Query structure returned by the parser, and
7 generate a plan used by the executor.  The /plan directory generates the
8 actual output plan, the /path code generates all possible ways to join the
9 tables, and /prep handles various preprocessing steps for special cases.
10 /util is utility stuff.  /geqo is the separate "genetic optimization" planner
11 --- it does a semi-random search through the join tree space, rather than
12 exhaustively considering all possible join trees.  (But each join considered
13 by /geqo is given to /path to create paths for, so we consider all possible
14 implementation paths for each specific join pair even in GEQO mode.)
15
16
17 Paths and Join Pairs
18 --------------------
19
20 During the planning/optimizing process, we build "Path" trees representing
21 the different ways of doing a query.  We select the cheapest Path that
22 generates the desired relation and turn it into a Plan to pass to the
23 executor.  (There is pretty much a one-to-one correspondence between the
24 Path and Plan trees, but Path nodes omit info that won't be needed during
25 planning, and include info needed for planning that won't be needed by the
26 executor.)
27
28 The optimizer builds a RelOptInfo structure for each base relation used in
29 the query.  Base rels are either primitive tables, or subquery subselects
30 that are planned via a separate recursive invocation of the planner.  A
31 RelOptInfo is also built for each join relation that is considered during
32 planning.  A join rel is simply a combination of base rels.  There is only
33 one join RelOptInfo for any given set of baserels --- for example, the join
34 {A B C} is represented by the same RelOptInfo no matter whether we build it
35 by joining A and B first and then adding C, or joining B and C first and
36 then adding A, etc.  These different means of building the joinrel are
37 represented as Paths.  For each RelOptInfo we build a list of Paths that
38 represent plausible ways to implement the scan or join of that relation.
39 Once we've considered all the plausible Paths for a rel, we select the one
40 that is cheapest according to the planner's cost estimates.  The final plan
41 is derived from the cheapest Path for the RelOptInfo that includes all the
42 base rels of the query.
43
44 Possible Paths for a primitive table relation include plain old sequential
45 scan, plus index scans for any indexes that exist on the table, plus bitmap
46 index scans using one or more indexes.  A subquery base relation just has
47 one Path, a "SubqueryScan" path (which links to the subplan that was built
48 by a recursive invocation of the planner).  Likewise a function-RTE base
49 relation has only one possible Path.
50
51 Joins always occur using two RelOptInfos.  One is outer, the other inner.
52 Outers drive lookups of values in the inner.  In a nested loop, lookups of
53 values in the inner occur by scanning the inner path once per outer tuple
54 to find each matching inner row.  In a mergejoin, inner and outer rows are
55 ordered, and are accessed in order, so only one scan is required to perform
56 the entire join: both inner and outer paths are scanned in-sync.  (There's
57 not a lot of difference between inner and outer in a mergejoin...)  In a
58 hashjoin, the inner is scanned first and all its rows are entered in a
59 hashtable, then the outer is scanned and for each row we lookup the join
60 key in the hashtable.
61
62 A Path for a join relation is actually a tree structure, with the top
63 Path node representing the join method.  It has left and right subpaths
64 that represent the scan or join methods used for the two input relations.
65
66
67 Join Tree Construction
68 ----------------------
69
70 The optimizer generates optimal query plans by doing a more-or-less
71 exhaustive search through the ways of executing the query.  The best Path
72 tree is found by a recursive process:
73
74 1) Take each base relation in the query, and make a RelOptInfo structure
75 for it.  Find each potentially useful way of accessing the relation,
76 including sequential and index scans, and make Paths representing those
77 ways.  All the Paths made for a given relation are placed in its
78 RelOptInfo.pathlist.  (Actually, we discard Paths that are obviously
79 inferior alternatives before they ever get into the pathlist --- what
80 ends up in the pathlist is the cheapest way of generating each potentially
81 useful sort ordering of the relation.)  Also create a RelOptInfo.joininfo
82 list including all the join clauses that involve this relation.  For
83 example, the WHERE clause "tab1.col1 = tab2.col1" generates entries in
84 both tab1 and tab2's joininfo lists.
85
86 If we have only a single base relation in the query, we are done.
87 Otherwise we have to figure out how to join the base relations into a
88 single join relation.
89
90 2) Normally, any explicit JOIN clauses are "flattened" so that we just
91 have a list of relations to join.  However, FULL OUTER JOIN clauses are
92 never flattened, and other kinds of JOIN might not be either, if the
93 flattening process is stopped by join_collapse_limit or from_collapse_limit
94 restrictions.  Therefore, we end up with a planning problem that contains
95 lists of relations to be joined in any order, where any individual item
96 might be a sub-list that has to be joined together before we can consider
97 joining it to its siblings.  We process these sub-problems recursively,
98 bottom up.  Note that the join list structure constrains the possible join
99 orders, but it doesn't constrain the join implementation method at each
100 join (nestloop, merge, hash), nor does it say which rel is considered outer
101 or inner at each join.  We consider all these possibilities in building
102 Paths. We generate a Path for each feasible join method, and select the
103 cheapest Path.
104
105 For each planning problem, therefore, we will have a list of relations
106 that are either base rels or joinrels constructed per sub-join-lists.
107 We can join these rels together in any order the planner sees fit.
108 The standard (non-GEQO) planner does this as follows:
109
110 Consider joining each RelOptInfo to each other RelOptInfo for which there
111 is a usable joinclause, and generate a Path for each possible join method
112 for each such pair.  (If we have a RelOptInfo with no join clauses, we have
113 no choice but to generate a clauseless Cartesian-product join; so we
114 consider joining that rel to each other available rel.  But in the presence
115 of join clauses we will only consider joins that use available join
116 clauses.  Note that join-order restrictions induced by outer joins and
117 IN clauses are treated as if they were real join clauses, to ensure that
118 we find a workable join order in cases where those restrictions force a
119 clauseless join to be done.)
120
121 If we only had two relations in the list, we are done: we just pick
122 the cheapest path for the join RelOptInfo.  If we had more than two, we now
123 need to consider ways of joining join RelOptInfos to each other to make
124 join RelOptInfos that represent more than two list items.
125
126 The join tree is constructed using a "dynamic programming" algorithm:
127 in the first pass (already described) we consider ways to create join rels
128 representing exactly two list items.  The second pass considers ways
129 to make join rels that represent exactly three list items; the next pass,
130 four items, etc.  The last pass considers how to make the final join
131 relation that includes all list items --- obviously there can be only one
132 join rel at this top level, whereas there can be more than one join rel
133 at lower levels.  At each level we use joins that follow available join
134 clauses, if possible, just as described for the first level.
135
136 For example:
137
138     SELECT  *
139     FROM    tab1, tab2, tab3, tab4
140     WHERE   tab1.col = tab2.col AND
141         tab2.col = tab3.col AND
142         tab3.col = tab4.col
143
144     Tables 1, 2, 3, and 4 are joined as:
145     {1 2},{2 3},{3 4}
146     {1 2 3},{2 3 4}
147     {1 2 3 4}
148     (other possibilities will be excluded for lack of join clauses)
149
150     SELECT  *
151     FROM    tab1, tab2, tab3, tab4
152     WHERE   tab1.col = tab2.col AND
153         tab1.col = tab3.col AND
154         tab1.col = tab4.col
155
156     Tables 1, 2, 3, and 4 are joined as:
157     {1 2},{1 3},{1 4}
158     {1 2 3},{1 3 4},{1 2 4}
159     {1 2 3 4}
160
161 We consider left-handed plans (the outer rel of an upper join is a joinrel,
162 but the inner is always a single list item); right-handed plans (outer rel
163 is always a single item); and bushy plans (both inner and outer can be
164 joins themselves).  For example, when building {1 2 3 4} we consider
165 joining {1 2 3} to {4} (left-handed), {4} to {1 2 3} (right-handed), and
166 {1 2} to {3 4} (bushy), among other choices.  Although the jointree
167 scanning code produces these potential join combinations one at a time,
168 all the ways to produce the same set of joined base rels will share the
169 same RelOptInfo, so the paths produced from different join combinations
170 that produce equivalent joinrels will compete in add_path().
171
172 Once we have built the final join rel, we use either the cheapest path
173 for it or the cheapest path with the desired ordering (if that's cheaper
174 than applying a sort to the cheapest other path).
175
176 If the query contains one-sided outer joins (LEFT or RIGHT joins), or
177 "IN (sub-select)" WHERE clauses that were converted to joins, then some of
178 the possible join orders may be illegal.  These are excluded by having
179 join_is_legal consult side lists of outer joins and IN joins to see
180 whether a proposed join is illegal.  (The same consultation allows it
181 to see which join style should be applied for a valid join, ie,
182 JOIN_INNER, JOIN_LEFT, etc.)
183
184
185 Valid OUTER JOIN Optimizations
186 ------------------------------
187
188 The planner's treatment of outer join reordering is based on the following
189 identities:
190
191 1.      (A leftjoin B on (Pab)) innerjoin C on (Pac)
192         = (A innerjoin C on (Pac)) leftjoin B on (Pab)
193
194 where Pac is a predicate referencing A and C, etc (in this case, clearly
195 Pac cannot reference B, or the transformation is nonsensical).
196
197 2.      (A leftjoin B on (Pab)) leftjoin C on (Pac)
198         = (A leftjoin C on (Pac)) leftjoin B on (Pab)
199
200 3.      (A leftjoin B on (Pab)) leftjoin C on (Pbc)
201         = A leftjoin (B leftjoin C on (Pbc)) on (Pab)
202
203 Identity 3 only holds if predicate Pbc must fail for all-null B rows
204 (that is, Pbc is strict for at least one column of B).  If Pbc is not
205 strict, the first form might produce some rows with nonnull C columns
206 where the second form would make those entries null.
207
208 RIGHT JOIN is equivalent to LEFT JOIN after switching the two input
209 tables, so the same identities work for right joins.  Only FULL JOIN
210 cannot be re-ordered at all.
211
212 An example of a case that does *not* work is moving an innerjoin into or
213 out of the nullable side of an outer join:
214
215         A leftjoin (B join C on (Pbc)) on (Pab)
216         != (A leftjoin B on (Pab)) join C on (Pbc)
217
218 FULL JOIN ordering is enforced by not collapsing FULL JOIN nodes when
219 translating the jointree to "joinlist" representation.  LEFT and RIGHT
220 JOIN nodes are normally collapsed so that they participate fully in the
221 join order search.  To avoid generating illegal join orders, the planner
222 creates an OuterJoinInfo node for each outer join, and join_is_legal
223 checks this list to decide if a proposed join is legal.
224
225 What we store in OuterJoinInfo nodes are the minimum sets of Relids
226 required on each side of the join to form the outer join.  Note that
227 these are minimums; there's no explicit maximum, since joining other
228 rels to the OJ's syntactic rels may be legal.  Per identities 1 and 2,
229 non-FULL joins can be freely associated into the lefthand side of an
230 OJ, but in general they can't be associated into the righthand side.
231 So the restriction enforced by join_is_legal is that a proposed join
232 can't join a rel within or partly within an RHS boundary to one outside
233 the boundary, unless the join validly implements some outer join.
234 (To support use of identity 3, we have to allow cases where an apparent
235 violation of a lower OJ's RHS is committed while forming an upper OJ.
236 If this wouldn't in fact be legal, the upper OJ's minimum LHS or RHS
237 set must be expanded to include the whole of the lower OJ, thereby
238 preventing it from being formed before the lower OJ is.)
239
240
241 Pulling Up Subqueries
242 ---------------------
243
244 As we described above, a subquery appearing in the range table is planned
245 independently and treated as a "black box" during planning of the outer
246 query.  This is necessary when the subquery uses features such as
247 aggregates, GROUP, or DISTINCT.  But if the subquery is just a simple
248 scan or join, treating the subquery as a black box may produce a poor plan
249 compared to considering it as part of the entire plan search space.
250 Therefore, at the start of the planning process the planner looks for
251 simple subqueries and pulls them up into the main query's jointree.
252
253 Pulling up a subquery may result in FROM-list joins appearing below the top
254 of the join tree.  Each FROM-list is planned using the dynamic-programming
255 search method described above.
256
257 If pulling up a subquery produces a FROM-list as a direct child of another
258 FROM-list, then we can merge the two FROM-lists together.  Once that's
259 done, the subquery is an absolutely integral part of the outer query and
260 will not constrain the join tree search space at all.  However, that could
261 result in unpleasant growth of planning time, since the dynamic-programming
262 search has runtime exponential in the number of FROM-items considered.
263 Therefore, we don't merge FROM-lists if the result would have too many
264 FROM-items in one list.
265
266
267 Optimizer Functions
268 -------------------
269
270 The primary entry point is planner().
271
272 planner()
273  set up for recursive handling of subqueries
274  do final cleanup after planning
275 -subquery_planner()
276  pull up subqueries from rangetable, if possible
277  canonicalize qual
278      Attempt to simplify WHERE clause to the most useful form; this includes
279      flattening nested AND/ORs and detecting clauses that are duplicated in
280      different branches of an OR.
281  simplify constant expressions
282  process sublinks
283  convert Vars of outer query levels into Params
284 --grouping_planner()
285   preprocess target list for non-SELECT queries
286   handle UNION/INTERSECT/EXCEPT, GROUP BY, HAVING, aggregates,
287         ORDER BY, DISTINCT, LIMIT
288 --query_planner()
289    pull out constant quals, which can be used to gate execution of the
290         whole plan (if any are found, we make a top-level Result node
291         to do the gating)
292    make list of base relations used in query
293    split up the qual into restrictions (a=1) and joins (b=c)
294    find qual clauses that enable merge and hash joins
295 ----make_one_rel()
296      set_base_rel_pathlist()
297       find seqscan and all index paths for each base relation
298       find selectivity of columns used in joins
299      make_rel_from_joinlist()
300       hand off join subproblems to a plugin, GEQO, or standard_join_search()
301 -----standard_join_search()
302       call join_search_one_level() for each level of join tree needed
303       join_search_one_level():
304         For each joinrel of the prior level, do make_rels_by_clause_joins()
305         if it has join clauses, or make_rels_by_clauseless_joins() if not.
306         Also generate "bushy plan" joins between joinrels of lower levels.
307       Back at standard_join_search(), apply set_cheapest() to extract the
308       cheapest path for each newly constructed joinrel.
309       Loop back if this wasn't the top join level.
310    Back at query_planner:
311     put back any constant quals by adding a Result node
312  Back at grouping_planner:
313  do grouping(GROUP)
314  do aggregates
315  make unique(DISTINCT)
316  make sort(ORDER BY)
317  make limit(LIMIT/OFFSET)
318
319
320 Optimizer Data Structures
321 -------------------------
322
323 PlannerGlobal   - global information for a single planner invocation
324
325 PlannerInfo     - information for planning a particular Query (we make
326                   a separate PlannerInfo node for each sub-Query)
327
328 RelOptInfo      - a relation or joined relations
329
330  RestrictInfo   - WHERE clauses, like "x = 3" or "y = z"
331                   (note the same structure is used for restriction and
332                    join clauses)
333
334  Path           - every way to generate a RelOptInfo(sequential,index,joins)
335   SeqScan       - a plain Path node with pathtype = T_SeqScan
336   IndexPath     - index scans
337   BitmapHeapPath - top of a bitmapped index scan
338   TidPath       - scan by CTID
339   AppendPath    - append multiple subpaths together
340   ResultPath    - a Result plan node (used for FROM-less SELECT)
341   MaterialPath  - a Material plan node
342   UniquePath    - remove duplicate rows
343   NestPath      - nested-loop joins
344   MergePath     - merge joins
345   HashPath      - hash joins
346
347  EquivalenceClass - a data structure representing a set of values known equal
348
349  PathKey        - a data structure representing the sort ordering of a path
350
351 The optimizer spends a good deal of its time worrying about the ordering
352 of the tuples returned by a path.  The reason this is useful is that by
353 knowing the sort ordering of a path, we may be able to use that path as
354 the left or right input of a mergejoin and avoid an explicit sort step.
355 Nestloops and hash joins don't really care what the order of their inputs
356 is, but mergejoin needs suitably ordered inputs.  Therefore, all paths
357 generated during the optimization process are marked with their sort order
358 (to the extent that it is known) for possible use by a higher-level merge.
359
360 It is also possible to avoid an explicit sort step to implement a user's
361 ORDER BY clause if the final path has the right ordering already, so the
362 sort ordering is of interest even at the top level.  query_planner() will
363 look for the cheapest path with a sort order matching the desired order,
364 and grouping_planner() will compare its cost to the cost of using the
365 cheapest-overall path and doing an explicit sort.
366
367 When we are generating paths for a particular RelOptInfo, we discard a path
368 if it is more expensive than another known path that has the same or better
369 sort order.  We will never discard a path that is the only known way to
370 achieve a given sort order (without an explicit sort, that is).  In this
371 way, the next level up will have the maximum freedom to build mergejoins
372 without sorting, since it can pick from any of the paths retained for its
373 inputs.
374
375
376 EquivalenceClasses
377 ------------------
378
379 During the deconstruct_jointree() scan of the query's qual clauses, we look
380 for mergejoinable equality clauses A = B whose applicability is not delayed
381 by an outer join; these are called "equivalence clauses".  When we find
382 one, we create an EquivalenceClass containing the expressions A and B to
383 record this knowledge.  If we later find another equivalence clause B = C,
384 we add C to the existing EquivalenceClass for {A B}; this may require
385 merging two existing EquivalenceClasses.  At the end of the scan, we have
386 sets of values that are known all transitively equal to each other.  We can
387 therefore use a comparison of any pair of the values as a restriction or
388 join clause (when these values are available at the scan or join, of
389 course); furthermore, we need test only one such comparison, not all of
390 them.  Therefore, equivalence clauses are removed from the standard qual
391 distribution process.  Instead, when preparing a restriction or join clause
392 list, we examine each EquivalenceClass to see if it can contribute a
393 clause, and if so we select an appropriate pair of values to compare.  For
394 example, if we are trying to join A's relation to C's, we can generate the
395 clause A = C, even though this appeared nowhere explicitly in the original
396 query.  This may allow us to explore join paths that otherwise would have
397 been rejected as requiring Cartesian-product joins.
398
399 Sometimes an EquivalenceClass may contain a pseudo-constant expression
400 (i.e., one not containing Vars or Aggs of the current query level, nor
401 volatile functions).  In this case we do not follow the policy of
402 dynamically generating join clauses: instead, we dynamically generate
403 restriction clauses "var = const" wherever one of the variable members of
404 the class can first be computed.  For example, if we have A = B and B = 42,
405 we effectively generate the restriction clauses A = 42 and B = 42, and then
406 we need not bother with explicitly testing the join clause A = B when the
407 relations are joined.  In effect, all the class members can be tested at
408 relation-scan level and there's never a need for join tests.
409
410 The precise technical interpretation of an EquivalenceClass is that it
411 asserts that at any plan node where more than one of its member values
412 can be computed, output rows in which the values are not all equal may
413 be discarded without affecting the query result.  (We require all levels
414 of the plan to enforce EquivalenceClasses, hence a join need not recheck
415 equality of values that were computable by one of its children.)  For an
416 ordinary EquivalenceClass that is "valid everywhere", we can further infer
417 that the values are all non-null, because all mergejoinable operators are
418 strict.  However, we also allow equivalence clauses that appear below the
419 nullable side of an outer join to form EquivalenceClasses; for these
420 classes, the interpretation is that either all the values are equal, or
421 all (except pseudo-constants) have gone to null.  (This requires a
422 limitation that non-constant members be strict, else they might not go
423 to null when the other members do.)  Consider for example
424
425         SELECT *
426           FROM a LEFT JOIN
427                (SELECT * FROM b JOIN c ON b.y = c.z WHERE b.y = 10) ss
428                ON a.x = ss.y
429           WHERE a.x = 42;
430
431 We can form the below-outer-join EquivalenceClass {b.y c.z 10} and thereby
432 apply c.z = 10 while scanning c.  (The reason we disallow outerjoin-delayed
433 clauses from forming EquivalenceClasses is exactly that we want to be able
434 to push any derived clauses as far down as possible.)  But once above the
435 outer join it's no longer necessarily the case that b.y = 10, and thus we
436 cannot use such EquivalenceClasses to conclude that sorting is unnecessary
437 (see discussion of PathKeys below).
438
439 In this example, notice also that a.x = ss.y (really a.x = b.y) is not an
440 equivalence clause because its applicability to b is delayed by the outer
441 join; thus we do not try to insert b.y into the equivalence class {a.x 42}.
442 But since we see that a.x has been equated to 42 above the outer join, we
443 are able to form a below-outer-join class {b.y 42}; this restriction can be
444 added because no b/c row not having b.y = 42 can contribute to the result
445 of the outer join, and so we need not compute such rows.  Now this class
446 will get merged with {b.y c.z 10}, leading to the contradiction 10 = 42,
447 which lets the planner deduce that the b/c join need not be computed at all
448 because none of its rows can contribute to the outer join.  (This gets
449 implemented as a gating Result filter, since more usually the potential
450 contradiction involves Param values rather than just Consts, and thus has
451 to be checked at runtime.)
452
453 To aid in determining the sort ordering(s) that can work with a mergejoin,
454 we mark each mergejoinable clause with the EquivalenceClasses of its left
455 and right inputs.  For an equivalence clause, these are of course the same
456 EquivalenceClass.  For a non-equivalence mergejoinable clause (such as an
457 outer-join qualification), we generate two separate EquivalenceClasses for
458 the left and right inputs.  This may result in creating single-item
459 equivalence "classes", though of course these are still subject to merging
460 if other equivalence clauses are later found to bear on the same
461 expressions.
462
463 Another way that we may form a single-item EquivalenceClass is in creation
464 of a PathKey to represent a desired sort order (see below).  This is a bit
465 different from the above cases because such an EquivalenceClass might
466 contain an aggregate function or volatile expression.  (A clause containing
467 a volatile function will never be considered mergejoinable, even if its top
468 operator is mergejoinable, so there is no way for a volatile expression to
469 get into EquivalenceClasses otherwise.  Aggregates are disallowed in WHERE
470 altogether, so will never be found in a mergejoinable clause.)  This is just
471 a convenience to maintain a uniform PathKey representation: such an
472 EquivalenceClass will never be merged with any other.
473
474 An EquivalenceClass also contains a list of btree opfamily OIDs, which
475 determines what the equalities it represents actually "mean".  All the
476 equivalence clauses that contribute to an EquivalenceClass must have
477 equality operators that belong to the same set of opfamilies.  (Note: most
478 of the time, a particular equality operator belongs to only one family, but
479 it's possible that it belongs to more than one.  We keep track of all the
480 families to ensure that we can make use of an index belonging to any one of
481 the families for mergejoin purposes.)
482
483
484 PathKeys
485 --------
486
487 The PathKeys data structure represents what is known about the sort order
488 of the tuples generated by a particular Path.  A path's pathkeys field is a
489 list of PathKey nodes, where the n'th item represents the n'th sort key of
490 the result.  Each PathKey contains these fields:
491
492         * a reference to an EquivalenceClass
493         * a btree opfamily OID (must match one of those in the EC)
494         * a sort direction (ascending or descending)
495         * a nulls-first-or-last flag
496
497 The EquivalenceClass represents the value being sorted on.  Since the
498 various members of an EquivalenceClass are known equal according to the
499 opfamily, we can consider a path sorted by any one of them to be sorted by
500 any other too; this is what justifies referencing the whole
501 EquivalenceClass rather than just one member of it.
502
503 In single/base relation RelOptInfo's, the Paths represent various ways
504 of scanning the relation and the resulting ordering of the tuples.
505 Sequential scan Paths have NIL pathkeys, indicating no known ordering.
506 Index scans have Path.pathkeys that represent the chosen index's ordering,
507 if any.  A single-key index would create a single-PathKey list, while a
508 multi-column index generates a list with one element per index column.
509 (Actually, since an index can be scanned either forward or backward, there
510 are two possible sort orders and two possible PathKey lists it can
511 generate.)
512
513 Note that a bitmap scan or multi-pass indexscan (OR clause scan) has NIL
514 pathkeys since we can say nothing about the overall order of its result.
515 Also, an indexscan on an unordered type of index generates NIL pathkeys.
516 However, we can always create a pathkey by doing an explicit sort.  The
517 pathkeys for a Sort plan's output just represent the sort key fields and
518 the ordering operators used.
519
520 Things get more interesting when we consider joins.  Suppose we do a
521 mergejoin between A and B using the mergeclause A.X = B.Y.  The output
522 of the mergejoin is sorted by X --- but it is also sorted by Y.  Again,
523 this can be represented by a PathKey referencing an EquivalenceClass
524 containing both X and Y.
525
526 With a little further thought, it becomes apparent that nestloop joins
527 can also produce sorted output.  For example, if we do a nestloop join
528 between outer relation A and inner relation B, then any pathkeys relevant
529 to A are still valid for the join result: we have not altered the order of
530 the tuples from A.  Even more interesting, if there was an equivalence clause
531 A.X=B.Y, and A.X was a pathkey for the outer relation A, then we can assert
532 that B.Y is a pathkey for the join result; X was ordered before and still
533 is, and the joined values of Y are equal to the joined values of X, so Y
534 must now be ordered too.  This is true even though we used neither an
535 explicit sort nor a mergejoin on Y.  (Note: hash joins cannot be counted
536 on to preserve the order of their outer relation, because the executor
537 might decide to "batch" the join, so we always set pathkeys to NIL for
538 a hashjoin path.)  Exception: a RIGHT or FULL join doesn't preserve the
539 ordering of its outer relation, because it might insert nulls at random
540 points in the ordering.
541
542 In general, we can justify using EquivalenceClasses as the basis for
543 pathkeys because, whenever we scan a relation containing multiple
544 EquivalenceClass members or join two relations each containing
545 EquivalenceClass members, we apply restriction or join clauses derived from
546 the EquivalenceClass.  This guarantees that any two values listed in the
547 EquivalenceClass are in fact equal in all tuples emitted by the scan or
548 join, and therefore that if the tuples are sorted by one of the values,
549 they can be considered sorted by any other as well.  It does not matter
550 whether the test clause is used as a mergeclause, or merely enforced
551 after-the-fact as a qpqual filter.
552
553 Note that there is no particular difficulty in labeling a path's sort
554 order with a PathKey referencing an EquivalenceClass that contains
555 variables not yet joined into the path's output.  We can simply ignore
556 such entries as not being relevant (yet).  This makes it possible to
557 use the same EquivalenceClasses throughout the join planning process.
558 In fact, by being careful not to generate multiple identical PathKey
559 objects, we can reduce comparison of EquivalenceClasses and PathKeys
560 to simple pointer comparison, which is a huge savings because add_path
561 has to make a large number of PathKey comparisons in deciding whether
562 competing Paths are equivalently sorted.
563
564 Pathkeys are also useful to represent an ordering that we wish to achieve,
565 since they are easily compared to the pathkeys of a potential candidate
566 path.  So, SortClause lists are turned into pathkeys lists for use inside
567 the optimizer.
568
569 Because we have to generate pathkeys lists from the sort clauses before
570 we've finished EquivalenceClass merging, we cannot use the pointer-equality
571 method of comparing PathKeys in the earliest stages of the planning
572 process.  Instead, we generate "non canonical" PathKeys that reference
573 single-element EquivalenceClasses that might get merged later.  After we
574 complete EquivalenceClass merging, we replace these with "canonical"
575 PathKeys that reference only fully-merged classes, and after that we make
576 sure we don't generate more than one copy of each "canonical" PathKey.
577 Then it is safe to use pointer comparison on canonical PathKeys.
578
579 An additional refinement we can make is to insist that canonical pathkey
580 lists (sort orderings) do not mention the same EquivalenceClass more than
581 once.  For example, in all these cases the second sort column is redundant,
582 because it cannot distinguish values that are the same according to the
583 first sort column:
584         SELECT ... ORDER BY x, x
585         SELECT ... ORDER BY x, x DESC
586         SELECT ... WHERE x = y ORDER BY x, y
587 Although a user probably wouldn't write "ORDER BY x,x" directly, such
588 redundancies are more probable once equivalence classes have been
589 considered.  Also, the system may generate redundant pathkey lists when
590 computing the sort ordering needed for a mergejoin.  By eliminating the
591 redundancy, we save time and improve planning, since the planner will more
592 easily recognize equivalent orderings as being equivalent.
593
594 Another interesting property is that if the underlying EquivalenceClass
595 contains a constant and is not below an outer join, then the pathkey is
596 completely redundant and need not be sorted by at all!  Every row must
597 contain the same constant value, so there's no need to sort.  (If the EC is
598 below an outer join, we still have to sort, since some of the rows might
599 have gone to null and others not.  In this case we must be careful to pick
600 a non-const member to sort by.  The assumption that all the non-const
601 members go to null at the same plan level is critical here, else they might
602 not produce the same sort order.)  This might seem pointless because users
603 are unlikely to write "... WHERE x = 42 ORDER BY x", but it allows us to
604 recognize when particular index columns are irrelevant to the sort order:
605 if we have "... WHERE x = 42 ORDER BY y", scanning an index on (x,y)
606 produces correctly ordered data without a sort step.  We used to have very
607 ugly ad-hoc code to recognize that in limited contexts, but discarding
608 constant ECs from pathkeys makes it happen cleanly and automatically.
609
610 You might object that a below-outer-join EquivalenceClass doesn't always
611 represent the same values at every level of the join tree, and so using
612 it to uniquely identify a sort order is dubious.  This is true, but we
613 can avoid dealing with the fact explicitly because we always consider that
614 an outer join destroys any ordering of its nullable inputs.  Thus, even
615 if a path was sorted by {a.x} below an outer join, we'll re-sort if that
616 sort ordering was important; and so using the same PathKey for both sort
617 orderings doesn't create any real problem.
618
619
620
621 Though Bob Devine <bob.devine@worldnet.att.net> was not involved in the 
622 coding of our optimizer, he is available to field questions about
623 optimizer topics.
624
625 -- bjm & tgl
626