Allow window functions to adjust their frameOptions
authorDavid Rowley <drowley@postgresql.org>
Thu, 22 Dec 2022 23:43:52 +0000 (12:43 +1300)
committerDavid Rowley <drowley@postgresql.org>
Thu, 22 Dec 2022 23:43:52 +0000 (12:43 +1300)
commited1a88ddaccfe883e4cf74d30319accfeae6cfe5
treeb3c2e52d5d70bc20b6fb9a1737f8647b4815934d
parentcc150596341e2a7913519769a88a1537c2e94720
Allow window functions to adjust their frameOptions

WindowFuncs such as row_number() don't care if it's called with ROWS
UNBOUNDED PRECEDING AND CURRENT ROW or with RANGE UNBOUNDED PRECEDING AND
CURRENT ROW.  The latter is less efficient as the RANGE option requires
that the executor check for peer rows, so using the ROW option instead
would cause less overhead.  Because RANGE is part of the default frame
options for WindowClauses, it means WindowAgg is, by default, working much
harder than it needs to for window functions where the ROWS / RANGE option
has no effect on the window function's result.

On a test query from the discussion thread, a performance improvement of
344% was seen by using ROWS instead of RANGE.

Here we add a new support function node type to allow support functions to
be called for window functions so that the most optimal version of the
frame options can be set.  The planner has been adjusted so that the frame
options are changed only if all window functions sharing the same window
clause agree on what the optimized frame options are.

Here we give the ability for row_number(), rank(), dense_rank(),
percent_rank(), cume_dist() and ntile() to alter their WindowClause's
frameOptions.

Reviewed-by: Vik Fearing, Erwin Brandstetter, Zhihong Yu
Discussion: https://postgr.es/m/CAGHENJ7LBBszxS+SkWWFVnBmOT2oVsBhDMB1DFrgerCeYa_DyA@mail.gmail.com
Discussion: https://postgr.es/m/CAApHDvohAKEtTXxq7Pc-ic2dKT8oZfbRKeEJP64M0B6+S88z+A@mail.gmail.com
src/backend/optimizer/plan/planner.c
src/backend/parser/parse_agg.c
src/backend/utils/adt/windowfuncs.c
src/include/catalog/catversion.h
src/include/catalog/pg_proc.dat
src/include/nodes/supportnodes.h
src/test/regress/expected/window.out
src/test/regress/sql/window.sql