pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedProposal: QUALIFY clause
41+ messages / 16 participants
[nested] [flat]
* Proposal: QUALIFY clause
@ 2025-07-21 12:47 Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
0 siblings, 2 replies; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-21 12:47 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
Hi all,
I'm sending a proof-of-concept patch to add support for the QUALIFY
clause in Postgres. This feature allows filtering rows after window
functions are computed, using a syntax similar to the WHERE or HAVING
clauses.
The idea for this came from a discussion and suggestion by Peter
Eisentraut (thanks, Peter!).
The `QUALIFY` clause is not part of the SQL standard, but it is
implemented by some major DBMSs, including Snowflake [1], BigQuery
[2] and DuckDB [3].
The goal is to provide a more ergonomic way to filter on window function
results without needing to nest subqueries or CTEs.
Simple example (see window.sql for more):
SELECT depname,
empno,
salary,
RANK() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
FROM empsalary
QUALIFY rnk = 1;
Please note that this is a proof-of-concept patch, I’m still working on
determining the best locations in the code to implement each part of the
logic for QUALIFY. I'm just sending this WIP to collect feedback and then
continue to work on the feature. Additionally, the current patch does not
handle yet expressions using AND/OR when referencing multiple window
function aliases (e.g., QUALIFY rnk = 1 AND rnk2 = 2).
Thoughts?
[1] https://docs.snowflake.com/en/sql-reference/constructs/qualify
[2] https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#qualify_clause
[3] https://duckdb.org/docs/stable/sql/query_syntax/qualify.html
--
Matheus Alcantara
Attachments:
v0-0001-QUALIFY-clause.patch (application/octet-stream, 22.0K) download
From cc323df48e7ccd50dae97419430741acd6eba24d Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <mths.dev@pm.me>
Date: Wed, 4 Jun 2025 15:56:59 -0300
Subject: [PATCH v0] QUALIFY clause
---
src/backend/optimizer/plan/planner.c | 5 ++
src/backend/parser/analyze.c | 8 +-
src/backend/parser/gram.y | 21 +++--
src/backend/parser/parse_agg.c | 7 +-
src/backend/parser/parse_clause.c | 57 +++++++++++-
src/backend/parser/parse_expr.c | 4 +
src/backend/parser/parse_func.c | 3 +
src/backend/parser/parse_relation.c | 18 ++++
src/include/nodes/parsenodes.h | 5 ++
src/include/parser/kwlist.h | 1 +
src/include/parser/parse_clause.h | 5 +-
src/include/parser/parse_node.h | 3 +
src/test/regress/expected/window.out | 125 +++++++++++++++++++++++++++
src/test/regress/sql/window.sql | 51 +++++++++++
14 files changed, 300 insertions(+), 13 deletions(-)
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 549aedcfa99..1a8fb387e47 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -4710,6 +4710,11 @@ create_one_window_path(PlannerInfo *root,
if (!topwindow)
topqual = lappend(topqual, opexpr);
}
+
+ /* Add QUALIFY qual */
+ if (wc->qualifyQual != NULL)
+ topqual = lappend(topqual, (Expr *) wc->qualifyQual);
+
}
path = (Path *)
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 34f7c17f576..dd27fd3730b 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -1481,9 +1481,12 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
qry->limitOption = stmt->limitOption;
/* transform window clauses after we have seen all window functions */
+ pstate->p_targetList = qry->targetList;
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
- &qry->targetList);
+ &qry->targetList,
+ stmt->qualifyClause);
+
/* resolve any still-unresolved output columns as being type text */
if (pstate->p_resolve_unknowns)
@@ -2975,7 +2978,8 @@ transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
/* transform window clauses after we have seen all window functions */
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
- &qry->targetList);
+ &qry->targetList,
+ NULL); /* FIXME(matheus) */
qry->rtable = pstate->p_rtable;
qry->rteperminfos = pstate->p_rteperminfos;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 73345bb3c70..63c0da99256 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -520,7 +520,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <node> TableElement TypedTableElement ConstraintElem DomainConstraintElem TableFuncElement
%type <node> columnDef columnOptions optionalPeriodName
%type <defelt> def_elem reloption_elem old_aggr_elem operator_def_elem
-%type <node> def_arg columnElem where_clause where_or_current_clause
+%type <node> def_arg columnElem where_clause qualify_clause where_or_current_clause
a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound
columnref having_clause func_table xmltable array_expr
OptWhereClause operator_def_arg
@@ -760,7 +760,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
- QUOTE QUOTES
+ QUALIFY QUOTE QUOTES
RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
@@ -12993,7 +12993,7 @@ select_clause:
*/
simple_select:
SELECT opt_all_clause opt_target_list
- into_clause from_clause where_clause
+ into_clause from_clause where_clause qualify_clause
group_clause having_clause window_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13002,10 +13002,11 @@ simple_select:
n->intoClause = $4;
n->fromClause = $5;
n->whereClause = $6;
- n->groupClause = ($7)->list;
- n->groupDistinct = ($7)->distinct;
- n->havingClause = $8;
- n->windowClause = $9;
+ n->qualifyClause = $7;
+ n->groupClause = ($8)->list;
+ n->groupDistinct = ($8)->distinct;
+ n->havingClause = $9;
+ n->windowClause = $10;
$$ = (Node *) n;
}
| SELECT distinct_clause target_list
@@ -14135,6 +14136,11 @@ where_clause:
| /*EMPTY*/ { $$ = NULL; }
;
+qualify_clause:
+ QUALIFY a_expr { $$ = $2; }
+ | /*EMPTY*/ { $$ = NULL; }
+ ;
+
/* variant for UPDATE and DELETE */
where_or_current_clause:
WHERE a_expr { $$ = $2; }
@@ -18250,6 +18256,7 @@ reserved_keyword:
| ORDER
| PLACING
| PRIMARY
+ | QUALIFY
| REFERENCES
| RETURNING
| SELECT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index 0ac8966e30f..deeb3584f97 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -402,6 +402,9 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
if (isAgg)
err = _("aggregate functions are not allowed in policy expressions");
@@ -878,8 +881,6 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_WHERE:
errkind = true;
break;
- case EXPR_KIND_POLICY:
- err = _("window functions are not allowed in policy expressions");
break;
case EXPR_KIND_HAVING:
errkind = true;
@@ -895,6 +896,8 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
err = _("window functions are not allowed in window definitions");
break;
case EXPR_KIND_SELECT_TARGET:
+ case EXPR_KIND_POLICY:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index 9f20a70ce13..75f5ab727f9 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -1842,6 +1842,51 @@ setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
}
}
+Node *
+transformQualifyClause(ParseState *pstate, List *targetlist, Node *qualify)
+{
+ Node *where;
+
+ if (qualify == NULL)
+ return NULL;
+
+ where = transformWhereClause(pstate,
+ qualify,
+ EXPR_KIND_QUALIFY,
+ "QUALIFY");
+
+ /*
+ * Transform any Var referencing a WindowFunc into a real WindowFunc de
+ * fact.
+ */
+ if (IsA(where, OpExpr))
+ {
+ ListCell *lc;
+ OpExpr *op = (OpExpr *) where;
+ List *newArgs = NIL;
+
+ foreach(lc, op->args)
+ {
+ Node *node = lfirst(lc);
+
+ if (IsA(node, Var))
+ {
+ Var *var = (Var *) node;
+ TargetEntry *tle = (TargetEntry *) lfirst(&targetlist->elements[var->varattno - 1]);
+
+
+ Assert(IsA(tle->expr, WindowFunc));
+ newArgs = lappend(newArgs, (Node *) tle->expr);
+ }
+ else
+ newArgs = lappend(newArgs, node);
+ }
+ op->args = newArgs;
+ }
+
+ return where;
+}
+
/*
* transformWhereClause -
@@ -2764,7 +2809,8 @@ transformSortClause(ParseState *pstate,
List *
transformWindowDefinitions(ParseState *pstate,
List *windowdefs,
- List **targetlist)
+ List **targetlist,
+ Node *qualify)
{
List *result = NIL;
Index winref = 0;
@@ -2776,6 +2822,7 @@ transformWindowDefinitions(ParseState *pstate,
WindowClause *refwc = NULL;
List *partitionClause;
List *orderClause;
+ Node *qualifyClause;
Oid rangeopfamily = InvalidOid;
Oid rangeopcintype = InvalidOid;
WindowClause *wc;
@@ -2824,12 +2871,20 @@ transformWindowDefinitions(ParseState *pstate,
EXPR_KIND_WINDOW_PARTITION,
true /* force SQL99 rules */ );
+ /*
+ * transform QUALIFY. targetlist is used find the window function
+ * reference.
+ *
+ */
+ qualifyClause = transformQualifyClause(pstate, *targetlist, qualify);
+
/*
* And prepare the new WindowClause.
*/
wc = makeNode(WindowClause);
wc->name = windef->name;
wc->refname = windef->refname;
+ wc->qualifyQual = qualifyClause;
/*
* Per spec, a windowdef that references a previous one copies the
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index d66276801c6..d30661e8da5 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -575,6 +575,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_COPY_WHERE:
case EXPR_KIND_GENERATED_COLUMN:
case EXPR_KIND_CYCLE_MARK:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
@@ -1794,6 +1795,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FROM_SUBSELECT:
case EXPR_KIND_FROM_FUNCTION:
case EXPR_KIND_WHERE:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
case EXPR_KIND_FILTER:
@@ -3219,6 +3221,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "GENERATED AS";
case EXPR_KIND_CYCLE_MARK:
return "CYCLE";
+ case EXPR_KIND_QUALIFY:
+ return "QUALIFY";
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 583bbbf232f..4e202949bfd 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -2557,6 +2557,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
err = _("set-returning functions are not allowed in policy expressions");
break;
diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c
index 04ecf64b1fc..d3bb9346dec 100644
--- a/src/backend/parser/parse_relation.c
+++ b/src/backend/parser/parse_relation.c
@@ -922,6 +922,24 @@ colNameToVar(ParseState *pstate, const char *colname, bool localonly,
newresult = scanNSItemForColumn(orig_pstate, nsitem, sublevels_up,
colname, location);
+ /*
+ * If we are parsing a QUALIFY expression try to search the window
+ * function reference on target list
+ */
+ if (newresult == NULL && orig_pstate->p_hasWindowFuncs
+ && pstate->p_expr_kind == EXPR_KIND_QUALIFY)
+ {
+ ListCell *lc;
+
+ foreach(lc, pstate->p_targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (strcmp(tle->resname, colname) == 0)
+ newresult = (Node *) makeVarFromTargetEntry(OUTER_VAR, tle);
+ }
+ }
+
if (newresult)
{
if (result)
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 86a236bd58b..824b7238ca9 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -220,6 +220,8 @@ typedef struct Query
Node *havingQual; /* qualifications applied to groups */
+ Node *qualifyQual; /* qualifications applied to window functions */
+
List *windowClause; /* a list of WindowClause's */
List *distinctClause; /* a list of SortGroupClause's */
@@ -1575,6 +1577,8 @@ typedef struct WindowClause
int frameOptions; /* frame_clause options, see WindowDef */
Node *startOffset; /* expression for starting bound, if any */
Node *endOffset; /* expression for ending bound, if any */
+ /* QUALIFY clause */
+ Node *qualifyQual;
/* in_range function for startOffset */
Oid startInRangeFunc pg_node_attr(query_jumble_ignore);
/* in_range function for endOffset */
@@ -2190,6 +2194,7 @@ typedef struct SelectStmt
List *targetList; /* the target list (of ResTarget) */
List *fromClause; /* the FROM clause */
Node *whereClause; /* WHERE qualification */
+ Node *qualifyClause; /* QUALIFY qualification */
List *groupClause; /* GROUP BY clauses */
bool groupDistinct; /* Is this GROUP BY DISTINCT? */
Node *havingClause; /* HAVING conditional-expression */
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index a4af3f717a1..f7e267dd241 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -359,6 +359,7 @@ PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("qualify", QUALIFY, RESERVED_KEYWORD, AS_LABEL)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("quotes", QUOTES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/include/parser/parse_clause.h b/src/include/parser/parse_clause.h
index 3e9894926de..5580842ee33 100644
--- a/src/include/parser/parse_clause.h
+++ b/src/include/parser/parse_clause.h
@@ -20,6 +20,8 @@ extern void transformFromClause(ParseState *pstate, List *frmList);
extern int setTargetTable(ParseState *pstate, RangeVar *relation,
bool inh, bool alsoSource, AclMode requiredPerms);
+
+extern Node * transformQualifyClause(ParseState *pstate, List *targetlist, Node *qualify);
extern Node *transformWhereClause(ParseState *pstate, Node *clause,
ParseExprKind exprKind, const char *constructName);
extern Node *transformLimitClause(ParseState *pstate, Node *clause,
@@ -35,7 +37,8 @@ extern List *transformSortClause(ParseState *pstate, List *orderlist,
extern List *transformWindowDefinitions(ParseState *pstate,
List *windowdefs,
- List **targetlist);
+ List **targetlist,
+ Node *qualify);
extern List *transformDistinctClause(ParseState *pstate,
List **targetlist, List *sortClause, bool is_agg);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f7d07c84542..05f0f17ba3d 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -45,6 +45,7 @@ typedef enum ParseExprKind
EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
EXPR_KIND_WHERE, /* WHERE */
EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_QUALIFY, /* QUALIFY */
EXPR_KIND_FILTER, /* FILTER */
EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
@@ -231,6 +232,8 @@ struct ParseState
Node *p_last_srf; /* most recent set-returning func/op found */
+ List *p_targetList; /* target list (of TargetEntry) */
+
/*
* Optional hook functions for parser callbacks. These are null unless
* set up by the caller of make_parsestate.
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index b86b668f433..5c886c06141 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -4537,6 +4537,131 @@ WHERE first_emp = 1 OR last_emp = 1;
sales | 4 | 4800 | 08-08-2007 | 3 | 1
(6 rows)
+-- Test QUALIFY clause
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+ depname | empno | salary | enroll_date | rank
+-----------+-------+--------+-------------+------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 2
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+ sales | 4 | 4800 | 08-08-2007 | 2
+ sales | 3 | 4800 | 08-01-2007 | 2
+(8 rows)
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC) = 1;
+ depname | empno | salary | enroll_date | row_number
+-----------+-------+--------+-------------+------------
+ develop | 7 | 4200 | 01-01-2008 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 1
+ sales | 4 | 4800 | 08-08-2007 | 1
+(3 rows)
+
+SELECT *,
+ AVG(salary) OVER (PARTITION BY depname) AS avg_salary
+FROM empsalary
+QUALIFY salary > avg_salary;
+ depname | empno | salary | enroll_date | avg_salary
+-----------+-------+--------+-------------+-----------------------
+ develop | 11 | 5200 | 08-15-2007 | 5020.0000000000000000
+ develop | 8 | 6000 | 10-01-2006 | 5020.0000000000000000
+ develop | 10 | 5200 | 08-01-2007 | 5020.0000000000000000
+ personnel | 2 | 3900 | 12-23-2006 | 3700.0000000000000000
+ sales | 1 | 5000 | 10-01-2006 | 4866.6666666666666667
+(5 rows)
+
+SELECT *,
+ COUNT(*) OVER (PARTITION BY depname, salary)
+FROM empsalary
+QUALIFY COUNT(*) OVER (PARTITION BY depname, salary) = 1;
+ depname | empno | salary | enroll_date | count
+-----------+-------+--------+-------------+-------
+ develop | 7 | 4200 | 01-01-2008 | 1
+ develop | 9 | 4500 | 01-01-2008 | 1
+ develop | 8 | 6000 | 10-01-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 1
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ sales | 1 | 5000 | 10-01-2006 | 1
+(6 rows)
+
+SELECT *,
+ RANK() OVER (ORDER BY salary DESC) as rank
+FROM empsalary
+QUALIFY rank = 2;
+ depname | empno | salary | enroll_date | rank
+---------+-------+--------+-------------+------
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 2
+(2 rows)
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date) <= 3;
+ depname | empno | salary | enroll_date | row_number
+-----------+-------+--------+-------------+------------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 3
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+ sales | 3 | 4800 | 08-01-2007 | 2
+ sales | 4 | 4800 | 08-08-2007 | 3
+(8 rows)
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC;
+ depname | empno | salary | enroll_date | row_number
+-----------+-------+--------+-------------+------------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ develop | 10 | 5200 | 08-01-2007 | 2
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+ sales | 4 | 4800 | 08-08-2007 | 2
+(6 rows)
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ AND enroll_date > DATE '2007-01-01';
+ depname | empno | salary | enroll_date | rank
+-----------+-------+--------+-------------+------
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 2
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 4 | 4800 | 08-08-2007 | 2
+ sales | 3 | 4800 | 08-01-2007 | 2
+(5 rows)
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ OR salary < 4000;
+ depname | empno | salary | enroll_date | rank
+-----------+-------+--------+-------------+------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+(4 rows)
+
-- cleanup
DROP TABLE empsalary;
-- test user-defined window function with named args and default args
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index 02f105f070e..4f376d1b459 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -1522,6 +1522,57 @@ SELECT * FROM
FROM empsalary) emp
WHERE first_emp = 1 OR last_emp = 1;
+-- Test QUALIFY clause
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC) = 1;
+
+SELECT *,
+ AVG(salary) OVER (PARTITION BY depname) AS avg_salary
+FROM empsalary
+QUALIFY salary > avg_salary;
+
+SELECT *,
+ COUNT(*) OVER (PARTITION BY depname, salary)
+FROM empsalary
+QUALIFY COUNT(*) OVER (PARTITION BY depname, salary) = 1;
+
+SELECT *,
+ RANK() OVER (ORDER BY salary DESC) as rank
+FROM empsalary
+QUALIFY rank = 2;
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date) <= 3;
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC;
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ AND enroll_date > DATE '2007-01-01';
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ OR salary < 4000;
+
-- cleanup
DROP TABLE empsalary;
--
2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-21 14:18 ` Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
1 sibling, 1 reply; 41+ messages in thread
From: Mike Artz @ 2025-07-21 14:18 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
Many times I have thought it would be nice if there was a QUALIFY clause in
Postgres!
Just would like to add that including your list, Teradata, Redshift, SAP
HANA, HP Vertica, and Trino all support the QUALIFY clause.
Also it seems Postgres would be the first leading RDBMS - meaning like
traditional, multipurpose RDMBS - to support QUALIFY, which would be pretty
cool.
On Mon, Jul 21, 2025 at 7:47 AM Matheus Alcantara <matheusssilv97@gmail.com>
wrote:
> Hi all,
>
> I'm sending a proof-of-concept patch to add support for the QUALIFY
> clause in Postgres. This feature allows filtering rows after window
> functions are computed, using a syntax similar to the WHERE or HAVING
> clauses.
>
> The idea for this came from a discussion and suggestion by Peter
> Eisentraut (thanks, Peter!).
>
> The `QUALIFY` clause is not part of the SQL standard, but it is
> implemented by some major DBMSs, including Snowflake [1], BigQuery
> [2] and DuckDB [3].
>
> The goal is to provide a more ergonomic way to filter on window function
> results without needing to nest subqueries or CTEs.
>
> Simple example (see window.sql for more):
>
> SELECT depname,
> empno,
> salary,
> RANK() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
> FROM empsalary
> QUALIFY rnk = 1;
>
> Please note that this is a proof-of-concept patch, I’m still working on
> determining the best locations in the code to implement each part of the
> logic for QUALIFY. I'm just sending this WIP to collect feedback and then
> continue to work on the feature. Additionally, the current patch does not
> handle yet expressions using AND/OR when referencing multiple window
> function aliases (e.g., QUALIFY rnk = 1 AND rnk2 = 2).
>
> Thoughts?
>
> [1] https://docs.snowflake.com/en/sql-reference/constructs/qualify
> [2]
> https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#qualify_clause
> [3] https://duckdb.org/docs/stable/sql/query_syntax/qualify.html
>
> --
> Matheus Alcantara
>
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
@ 2025-07-21 14:29 ` Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:41 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 14:47 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 2 replies; 41+ messages in thread
From: Isaac Morland @ 2025-07-21 14:29 UTC (permalink / raw)
To: Mike Artz <michaeleartz@gmail.com>; +Cc: Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, 21 Jul 2025 at 10:19, Mike Artz <michaeleartz@gmail.com> wrote:
> Many times I have thought it would be nice if there was a QUALIFY clause
> in Postgres!
>
> Just would like to add that including your list, Teradata, Redshift, SAP
> HANA, HP Vertica, and Trino all support the QUALIFY clause.
>
> Also it seems Postgres would be the first leading RDBMS - meaning like
> traditional, multipurpose RDMBS - to support QUALIFY, which would be pretty
> cool.
>
Is this different from using the window functions in a subquery and then
applying a WHERE clause on the outer query?
SELECT … FROM (SELECT … [including window functions] FROM …) WHERE [stuff
that would be in QUALIFY]
I'll be honest, I'm skeptical that we need another keyword that basically
means “WHERE, but applied at a different point in the query processing”.
I'm not even convinced that HAVING was a good idea (although obviously I
would not propose removal).
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
@ 2025-07-21 14:41 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 20:20 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
1 sibling, 1 reply; 41+ messages in thread
From: Tom Lane @ 2025-07-21 14:41 UTC (permalink / raw)
To: Isaac Morland <isaac.morland@gmail.com>; +Cc: Mike Artz <michaeleartz@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
Isaac Morland <isaac.morland@gmail.com> writes:
> I'll be honest, I'm skeptical that we need another keyword that basically
> means “WHERE, but applied at a different point in the query processing”.
That was my reaction too. I'm especially skeptical that getting out
front of the SQL standards committee is a good thing to do. If and
when this shows up in the standard, then sure.
regards, tom lane
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:41 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-07-21 20:20 ` Vik Fearing <vik@postgresfriends.org>
0 siblings, 0 replies; 41+ messages in thread
From: Vik Fearing @ 2025-07-21 20:20 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; Isaac Morland <isaac.morland@gmail.com>; +Cc: Mike Artz <michaeleartz@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 21/07/2025 16:41, Tom Lane wrote:
> Isaac Morland <isaac.morland@gmail.com> writes:
>> I'll be honest, I'm skeptical that we need another keyword that basically
>> means “WHERE, but applied at a different point in the query processing”.
> That was my reaction too. I'm especially skeptical that getting out
> front of the SQL standards committee is a good thing to do. If and
> when this shows up in the standard, then sure.
It's "when", not "if". I submitted a paper for this to the committee
two years ago, but it was just a discussion paper and not an actual
change proposal. I have recently revived that paper so hopefully it
will be accepted within the next year. I would even like to push so
that we have it in 19.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
@ 2025-07-21 14:47 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 17:30 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-21 14:47 UTC (permalink / raw)
To: Isaac Morland <isaac.morland@gmail.com>; Mike Artz <michaeleartz@gmail.com>; +Cc: pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon Jul 21, 2025 at 11:29 AM -03, Isaac Morland wrote:
> Is this different from using the window functions in a subquery and then
> applying a WHERE clause on the outer query?
>
> SELECT … FROM (SELECT … [including window functions] FROM …) WHERE [stuff
> that would be in QUALIFY]
>
> I'll be honest, I'm skeptical that we need another keyword that basically
> means “WHERE, but applied at a different point in the query processing”.
> I'm not even convinced that HAVING was a good idea (although obviously I
> would not propose removal).
>
Thanks for sharing your thoughts!
You're right — semantically, using QUALIFY is equivalent to wrapping the
query in a subquery and applying a WHERE clause to the result. The main
motivation here is to provide a more ergonomic and readable syntax.
While I understand the hesitation around introducing another keyword
that effectively acts like WHERE at a different stage, I believe QUALIFY
improves clarity in many use cases, by avoiding the boilerplate and
visual noise of nested subqueries making it easier to write and reason
about.
--
Matheus Alcantara
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:47 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-21 17:30 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 18:31 ` Re: Proposal: QUALIFY clause Thom Brown <thom@linux.com>
2025-07-21 20:26 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
0 siblings, 2 replies; 41+ messages in thread
From: Tom Lane @ 2025-07-21 17:30 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Isaac Morland <isaac.morland@gmail.com>; Mike Artz <michaeleartz@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
"Matheus Alcantara" <matheusssilv97@gmail.com> writes:
> You're right — semantically, using QUALIFY is equivalent to wrapping the
> query in a subquery and applying a WHERE clause to the result. The main
> motivation here is to provide a more ergonomic and readable syntax.
> While I understand the hesitation around introducing another keyword
> that effectively acts like WHERE at a different stage, I believe QUALIFY
> improves clarity in many use cases, by avoiding the boilerplate and
> visual noise of nested subqueries making it easier to write and reason
> about.
There are concrete reasons not to do this until/unless it becomes
standardized:
* If the syntax is like WHERE, there will be no way to do it without
making QUALIFY a fully-reserved word. That will inevitably break
more than zero applications. It's a lot easier to justify that
sort of breakage if we can say "QUALIFY is reserved according to
SQL:20xx, so don't blame us".
* I'm not exactly convinced that the committee would standardize
it just like this. For one thing, QUALIFY is not even the right
part of speech: it's a verb, and thus more fit to be a primary
statement keyword. What you need here is an adverb (I think ...
been a long time since high school English, but my dictionary
says WHERE is an adverb). Maybe they'd be persuaded to do what
the existing implementations did, but I wouldn't be at all surprised
if they choose a different keyword.
regards, tom lane
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:47 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 17:30 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-07-21 18:31 ` Thom Brown <thom@linux.com>
2025-07-21 18:38 ` Re: Proposal: QUALIFY clause Marko Tiikkaja <marko@joh.to>
1 sibling, 1 reply; 41+ messages in thread
From: Thom Brown @ 2025-07-21 18:31 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Matheus Alcantara <matheusssilv97@gmail.com>; Isaac Morland <isaac.morland@gmail.com>; Mike Artz <michaeleartz@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, 21 Jul 2025, 18:31 Tom Lane, <tgl@sss.pgh.pa.us> wrote:
> "Matheus Alcantara" <matheusssilv97@gmail.com> writes:
> > You're right — semantically, using QUALIFY is equivalent to wrapping the
> > query in a subquery and applying a WHERE clause to the result. The main
> > motivation here is to provide a more ergonomic and readable syntax.
>
> > While I understand the hesitation around introducing another keyword
> > that effectively acts like WHERE at a different stage, I believe QUALIFY
> > improves clarity in many use cases, by avoiding the boilerplate and
> > visual noise of nested subqueries making it easier to write and reason
> > about.
>
> There are concrete reasons not to do this until/unless it becomes
> standardized:
>
> * If the syntax is like WHERE, there will be no way to do it without
> making QUALIFY a fully-reserved word. That will inevitably break
> more than zero applications. It's a lot easier to justify that
> sort of breakage if we can say "QUALIFY is reserved according to
> SQL:20xx, so don't blame us".
>
> * I'm not exactly convinced that the committee would standardize
> it just like this. For one thing, QUALIFY is not even the right
> part of speech: it's a verb, and thus more fit to be a primary
> statement keyword. What you need here is an adverb (I think ...
> been a long time since high school English, but my dictionary
> says WHERE is an adverb). Maybe they'd be persuaded to do what
> the existing implementations did, but I wouldn't be at all surprised
> if they choose a different keyword.
>
I know we're not bikeshedding, but the word REFINE might be more
appropriate.
Thom
>
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:47 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 17:30 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 18:31 ` Re: Proposal: QUALIFY clause Thom Brown <thom@linux.com>
@ 2025-07-21 18:38 ` Marko Tiikkaja <marko@joh.to>
0 siblings, 0 replies; 41+ messages in thread
From: Marko Tiikkaja @ 2025-07-21 18:38 UTC (permalink / raw)
To: Thom Brown <thom@linux.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Matheus Alcantara <matheusssilv97@gmail.com>; Isaac Morland <isaac.morland@gmail.com>; Mike Artz <michaeleartz@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, Jul 21, 2025 at 9:32 PM Thom Brown <thom@linux.com> wrote:
>> * I'm not exactly convinced that the committee would standardize
>> it just like this. For one thing, QUALIFY is not even the right
>> part of speech: it's a verb, and thus more fit to be a primary
>> statement keyword. What you need here is an adverb (I think ...
>> been a long time since high school English, but my dictionary
>> says WHERE is an adverb). Maybe they'd be persuaded to do what
>> the existing implementations did, but I wouldn't be at all surprised
>> if they choose a different keyword.
>
>
> I know we're not bikeshedding, but the word REFINE might be more appropriate.
I vote for DONTGIMMEDAT.
.m
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:47 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 17:30 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-07-21 20:26 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 20:34 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
1 sibling, 1 reply; 41+ messages in thread
From: Vik Fearing @ 2025-07-21 20:26 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Isaac Morland <isaac.morland@gmail.com>; Mike Artz <michaeleartz@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 21/07/2025 19:30, Tom Lane wrote:
> "Matheus Alcantara" <matheusssilv97@gmail.com> writes:
>> You're right — semantically, using QUALIFY is equivalent to wrapping the
>> query in a subquery and applying a WHERE clause to the result. The main
>> motivation here is to provide a more ergonomic and readable syntax.
>> While I understand the hesitation around introducing another keyword
>> that effectively acts like WHERE at a different stage, I believe QUALIFY
>> improves clarity in many use cases, by avoiding the boilerplate and
>> visual noise of nested subqueries making it easier to write and reason
>> about.
> There are concrete reasons not to do this until/unless it becomes
> standardized:
>
> * If the syntax is like WHERE, there will be no way to do it without
> making QUALIFY a fully-reserved word. That will inevitably break
> more than zero applications. It's a lot easier to justify that
> sort of breakage if we can say "QUALIFY is reserved according to
> SQL:20xx, so don't blame us".
Yes, it will need to be reserved.
> * I'm not exactly convinced that the committee would standardize
> it just like this. For one thing, QUALIFY is not even the right
> part of speech: it's a verb, and thus more fit to be a primary
> statement keyword. What you need here is an adverb (I think ...
> been a long time since high school English, but my dictionary
> says WHERE is an adverb). Maybe they'd be persuaded to do what
> the existing implementations did, but I wouldn't be at all surprised
> if they choose a different keyword.
I am pretty sure that the keyword will be QUALIFY. There are just too
many existing implementations for the standard to go against them all.
(Also, another rdbms just implemented it that way in their upcoming
product.)
I agree that we should hold back until the standard accepts it, but
having a working patch ready to go seems like a good idea.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Re: Proposal: QUALIFY clause Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Re: Proposal: QUALIFY clause Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:47 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 17:30 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 20:26 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-21 20:34 ` Nico Williams <nico@cryptonector.com>
0 siblings, 0 replies; 41+ messages in thread
From: Nico Williams @ 2025-07-21 20:34 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Matheus Alcantara <matheusssilv97@gmail.com>; Isaac Morland <isaac.morland@gmail.com>; Mike Artz <michaeleartz@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, Jul 21, 2025 at 10:26:51PM +0200, Vik Fearing wrote:
> On 21/07/2025 19:30, Tom Lane wrote:
> > * I'm not exactly convinced that the committee would standardize
> > it just like this. For one thing, QUALIFY is not even the right
> > part of speech: it's a verb, and thus more fit to be a primary
> > statement keyword. What you need here is an adverb (I think ...
> > been a long time since high school English, but my dictionary
> > says WHERE is an adverb). Maybe they'd be persuaded to do what
> > the existing implementations did, but I wouldn't be at all surprised
> > if they choose a different keyword.
Or a gerund, which is what HAVING is. Or a conjugated verb or something
like QUALIFIED BY, though really "qualif*" seems just wrong. This is
just another name for a WHERE that, like HAVING is paired with some
other language feature (like GROUP BY) and applies to that clause. I
don't have a better keyword(s) to offer, just sadness.
> I am pretty sure that the keyword will be QUALIFY. There are just too many
> existing implementations for the standard to go against them all. (Also,
> another rdbms just implemented it that way in their upcoming product.)
Bummer.
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-21 20:23 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
1 sibling, 1 reply; 41+ messages in thread
From: Vik Fearing @ 2025-07-21 20:23 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
On 21/07/2025 14:47, Matheus Alcantara wrote:
> Hi all,
>
> I'm sending a proof-of-concept patch to add support for the QUALIFY
> clause in Postgres. This feature allows filtering rows after window
> functions are computed, using a syntax similar to the WHERE or HAVING
> clauses.
I took a very brief look at this, and I think your grammar is wrong.
The QUALIFY clause should go after the WINDOW clause, just like
FROM/WHERE and GROUP BY/HAVING.
That is what I am proposing to the standards committee, and I already
have some buy-in for that.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-21 21:29 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
0 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-21 21:29 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
On Mon Jul 21, 2025 at 5:23 PM -03, Vik Fearing wrote:
>
> On 21/07/2025 14:47, Matheus Alcantara wrote:
>> Hi all,
>>
>> I'm sending a proof-of-concept patch to add support for the QUALIFY
>> clause in Postgres. This feature allows filtering rows after window
>> functions are computed, using a syntax similar to the WHERE or HAVING
>> clauses.
>
>
> I took a very brief look at this, and I think your grammar is wrong.
> The QUALIFY clause should go after the WINDOW clause, just like
> FROM/WHERE and GROUP BY/HAVING.
>
>
> That is what I am proposing to the standards committee, and I already
> have some buy-in for that.
>
Thank you for the brief review and for the comments!
I'm not sure if I fully understand but please see the new attached
version.
Thanks,
--
Matheus Alcantara
Attachments:
v1-0001-QUALIFY-clause.patch (text/plain, 21.7K) download
From 28a4d49c27ba039518d3272aa35cb0176bab7750 Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <mths.dev@pm.me>
Date: Wed, 4 Jun 2025 15:56:59 -0300
Subject: [PATCH v1] QUALIFY clause
---
src/backend/optimizer/plan/planner.c | 5 ++
src/backend/parser/analyze.c | 8 +-
src/backend/parser/gram.y | 13 ++-
src/backend/parser/parse_agg.c | 7 +-
src/backend/parser/parse_clause.c | 57 +++++++++++-
src/backend/parser/parse_expr.c | 4 +
src/backend/parser/parse_func.c | 3 +
src/backend/parser/parse_relation.c | 18 ++++
src/include/nodes/parsenodes.h | 5 ++
src/include/parser/kwlist.h | 1 +
src/include/parser/parse_clause.h | 5 +-
src/include/parser/parse_node.h | 3 +
src/test/regress/expected/window.out | 125 +++++++++++++++++++++++++++
src/test/regress/sql/window.sql | 51 +++++++++++
14 files changed, 296 insertions(+), 9 deletions(-)
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 549aedcfa99..1a8fb387e47 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -4710,6 +4710,11 @@ create_one_window_path(PlannerInfo *root,
if (!topwindow)
topqual = lappend(topqual, opexpr);
}
+
+ /* Add QUALIFY qual */
+ if (wc->qualifyQual != NULL)
+ topqual = lappend(topqual, (Expr *) wc->qualifyQual);
+
}
path = (Path *)
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 34f7c17f576..dd27fd3730b 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -1481,9 +1481,12 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
qry->limitOption = stmt->limitOption;
/* transform window clauses after we have seen all window functions */
+ pstate->p_targetList = qry->targetList;
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
- &qry->targetList);
+ &qry->targetList,
+ stmt->qualifyClause);
+
/* resolve any still-unresolved output columns as being type text */
if (pstate->p_resolve_unknowns)
@@ -2975,7 +2978,8 @@ transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
/* transform window clauses after we have seen all window functions */
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
- &qry->targetList);
+ &qry->targetList,
+ NULL); /* FIXME(matheus) */
qry->rtable = pstate->p_rtable;
qry->rteperminfos = pstate->p_rteperminfos;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 73345bb3c70..117f20c8fa2 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -520,7 +520,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <node> TableElement TypedTableElement ConstraintElem DomainConstraintElem TableFuncElement
%type <node> columnDef columnOptions optionalPeriodName
%type <defelt> def_elem reloption_elem old_aggr_elem operator_def_elem
-%type <node> def_arg columnElem where_clause where_or_current_clause
+%type <node> def_arg columnElem where_clause qualify_clause where_or_current_clause
a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound
columnref having_clause func_table xmltable array_expr
OptWhereClause operator_def_arg
@@ -760,7 +760,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
- QUOTE QUOTES
+ QUALIFY QUOTE QUOTES
RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
@@ -12994,7 +12994,7 @@ select_clause:
simple_select:
SELECT opt_all_clause opt_target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13006,6 +13006,7 @@ simple_select:
n->groupDistinct = ($7)->distinct;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| SELECT distinct_clause target_list
@@ -14135,6 +14136,11 @@ where_clause:
| /*EMPTY*/ { $$ = NULL; }
;
+qualify_clause:
+ QUALIFY a_expr { $$ = $2; }
+ | /*EMPTY*/ { $$ = NULL; }
+ ;
+
/* variant for UPDATE and DELETE */
where_or_current_clause:
WHERE a_expr { $$ = $2; }
@@ -18250,6 +18256,7 @@ reserved_keyword:
| ORDER
| PLACING
| PRIMARY
+ | QUALIFY
| REFERENCES
| RETURNING
| SELECT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index 0ac8966e30f..deeb3584f97 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -402,6 +402,9 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
if (isAgg)
err = _("aggregate functions are not allowed in policy expressions");
@@ -878,8 +881,6 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_WHERE:
errkind = true;
break;
- case EXPR_KIND_POLICY:
- err = _("window functions are not allowed in policy expressions");
break;
case EXPR_KIND_HAVING:
errkind = true;
@@ -895,6 +896,8 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
err = _("window functions are not allowed in window definitions");
break;
case EXPR_KIND_SELECT_TARGET:
+ case EXPR_KIND_POLICY:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index 9f20a70ce13..75f5ab727f9 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -1842,6 +1842,51 @@ setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
}
}
+Node *
+transformQualifyClause(ParseState *pstate, List *targetlist, Node *qualify)
+{
+ Node *where;
+
+ if (qualify == NULL)
+ return NULL;
+
+ where = transformWhereClause(pstate,
+ qualify,
+ EXPR_KIND_QUALIFY,
+ "QUALIFY");
+
+ /*
+ * Transform any Var referencing a WindowFunc into a real WindowFunc de
+ * fact.
+ */
+ if (IsA(where, OpExpr))
+ {
+ ListCell *lc;
+ OpExpr *op = (OpExpr *) where;
+ List *newArgs = NIL;
+
+ foreach(lc, op->args)
+ {
+ Node *node = lfirst(lc);
+
+ if (IsA(node, Var))
+ {
+ Var *var = (Var *) node;
+ TargetEntry *tle = (TargetEntry *) lfirst(&targetlist->elements[var->varattno - 1]);
+
+
+ Assert(IsA(tle->expr, WindowFunc));
+ newArgs = lappend(newArgs, (Node *) tle->expr);
+ }
+ else
+ newArgs = lappend(newArgs, node);
+ }
+ op->args = newArgs;
+ }
+
+ return where;
+}
+
/*
* transformWhereClause -
@@ -2764,7 +2809,8 @@ transformSortClause(ParseState *pstate,
List *
transformWindowDefinitions(ParseState *pstate,
List *windowdefs,
- List **targetlist)
+ List **targetlist,
+ Node *qualify)
{
List *result = NIL;
Index winref = 0;
@@ -2776,6 +2822,7 @@ transformWindowDefinitions(ParseState *pstate,
WindowClause *refwc = NULL;
List *partitionClause;
List *orderClause;
+ Node *qualifyClause;
Oid rangeopfamily = InvalidOid;
Oid rangeopcintype = InvalidOid;
WindowClause *wc;
@@ -2824,12 +2871,20 @@ transformWindowDefinitions(ParseState *pstate,
EXPR_KIND_WINDOW_PARTITION,
true /* force SQL99 rules */ );
+ /*
+ * transform QUALIFY. targetlist is used find the window function
+ * reference.
+ *
+ */
+ qualifyClause = transformQualifyClause(pstate, *targetlist, qualify);
+
/*
* And prepare the new WindowClause.
*/
wc = makeNode(WindowClause);
wc->name = windef->name;
wc->refname = windef->refname;
+ wc->qualifyQual = qualifyClause;
/*
* Per spec, a windowdef that references a previous one copies the
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index d66276801c6..d30661e8da5 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -575,6 +575,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_COPY_WHERE:
case EXPR_KIND_GENERATED_COLUMN:
case EXPR_KIND_CYCLE_MARK:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
@@ -1794,6 +1795,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FROM_SUBSELECT:
case EXPR_KIND_FROM_FUNCTION:
case EXPR_KIND_WHERE:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
case EXPR_KIND_FILTER:
@@ -3219,6 +3221,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "GENERATED AS";
case EXPR_KIND_CYCLE_MARK:
return "CYCLE";
+ case EXPR_KIND_QUALIFY:
+ return "QUALIFY";
/*
* There is intentionally no default: case here, so that the
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 583bbbf232f..4e202949bfd 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -2557,6 +2557,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
err = _("set-returning functions are not allowed in policy expressions");
break;
diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c
index 04ecf64b1fc..d3bb9346dec 100644
--- a/src/backend/parser/parse_relation.c
+++ b/src/backend/parser/parse_relation.c
@@ -922,6 +922,24 @@ colNameToVar(ParseState *pstate, const char *colname, bool localonly,
newresult = scanNSItemForColumn(orig_pstate, nsitem, sublevels_up,
colname, location);
+ /*
+ * If we are parsing a QUALIFY expression try to search the window
+ * function reference on target list
+ */
+ if (newresult == NULL && orig_pstate->p_hasWindowFuncs
+ && pstate->p_expr_kind == EXPR_KIND_QUALIFY)
+ {
+ ListCell *lc;
+
+ foreach(lc, pstate->p_targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (strcmp(tle->resname, colname) == 0)
+ newresult = (Node *) makeVarFromTargetEntry(OUTER_VAR, tle);
+ }
+ }
+
if (newresult)
{
if (result)
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 86a236bd58b..824b7238ca9 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -220,6 +220,8 @@ typedef struct Query
Node *havingQual; /* qualifications applied to groups */
+ Node *qualifyQual; /* qualifications applied to window functions */
+
List *windowClause; /* a list of WindowClause's */
List *distinctClause; /* a list of SortGroupClause's */
@@ -1575,6 +1577,8 @@ typedef struct WindowClause
int frameOptions; /* frame_clause options, see WindowDef */
Node *startOffset; /* expression for starting bound, if any */
Node *endOffset; /* expression for ending bound, if any */
+ /* QUALIFY clause */
+ Node *qualifyQual;
/* in_range function for startOffset */
Oid startInRangeFunc pg_node_attr(query_jumble_ignore);
/* in_range function for endOffset */
@@ -2190,6 +2194,7 @@ typedef struct SelectStmt
List *targetList; /* the target list (of ResTarget) */
List *fromClause; /* the FROM clause */
Node *whereClause; /* WHERE qualification */
+ Node *qualifyClause; /* QUALIFY qualification */
List *groupClause; /* GROUP BY clauses */
bool groupDistinct; /* Is this GROUP BY DISTINCT? */
Node *havingClause; /* HAVING conditional-expression */
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index a4af3f717a1..f7e267dd241 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -359,6 +359,7 @@ PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("qualify", QUALIFY, RESERVED_KEYWORD, AS_LABEL)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("quotes", QUOTES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/include/parser/parse_clause.h b/src/include/parser/parse_clause.h
index 3e9894926de..5580842ee33 100644
--- a/src/include/parser/parse_clause.h
+++ b/src/include/parser/parse_clause.h
@@ -20,6 +20,8 @@ extern void transformFromClause(ParseState *pstate, List *frmList);
extern int setTargetTable(ParseState *pstate, RangeVar *relation,
bool inh, bool alsoSource, AclMode requiredPerms);
+
+extern Node * transformQualifyClause(ParseState *pstate, List *targetlist, Node *qualify);
extern Node *transformWhereClause(ParseState *pstate, Node *clause,
ParseExprKind exprKind, const char *constructName);
extern Node *transformLimitClause(ParseState *pstate, Node *clause,
@@ -35,7 +37,8 @@ extern List *transformSortClause(ParseState *pstate, List *orderlist,
extern List *transformWindowDefinitions(ParseState *pstate,
List *windowdefs,
- List **targetlist);
+ List **targetlist,
+ Node *qualify);
extern List *transformDistinctClause(ParseState *pstate,
List **targetlist, List *sortClause, bool is_agg);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f7d07c84542..05f0f17ba3d 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -45,6 +45,7 @@ typedef enum ParseExprKind
EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
EXPR_KIND_WHERE, /* WHERE */
EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_QUALIFY, /* QUALIFY */
EXPR_KIND_FILTER, /* FILTER */
EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
@@ -231,6 +232,8 @@ struct ParseState
Node *p_last_srf; /* most recent set-returning func/op found */
+ List *p_targetList; /* target list (of TargetEntry) */
+
/*
* Optional hook functions for parser callbacks. These are null unless
* set up by the caller of make_parsestate.
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index b86b668f433..5c886c06141 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -4537,6 +4537,131 @@ WHERE first_emp = 1 OR last_emp = 1;
sales | 4 | 4800 | 08-08-2007 | 3 | 1
(6 rows)
+-- Test QUALIFY clause
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+ depname | empno | salary | enroll_date | rank
+-----------+-------+--------+-------------+------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 2
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+ sales | 4 | 4800 | 08-08-2007 | 2
+ sales | 3 | 4800 | 08-01-2007 | 2
+(8 rows)
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC) = 1;
+ depname | empno | salary | enroll_date | row_number
+-----------+-------+--------+-------------+------------
+ develop | 7 | 4200 | 01-01-2008 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 1
+ sales | 4 | 4800 | 08-08-2007 | 1
+(3 rows)
+
+SELECT *,
+ AVG(salary) OVER (PARTITION BY depname) AS avg_salary
+FROM empsalary
+QUALIFY salary > avg_salary;
+ depname | empno | salary | enroll_date | avg_salary
+-----------+-------+--------+-------------+-----------------------
+ develop | 11 | 5200 | 08-15-2007 | 5020.0000000000000000
+ develop | 8 | 6000 | 10-01-2006 | 5020.0000000000000000
+ develop | 10 | 5200 | 08-01-2007 | 5020.0000000000000000
+ personnel | 2 | 3900 | 12-23-2006 | 3700.0000000000000000
+ sales | 1 | 5000 | 10-01-2006 | 4866.6666666666666667
+(5 rows)
+
+SELECT *,
+ COUNT(*) OVER (PARTITION BY depname, salary)
+FROM empsalary
+QUALIFY COUNT(*) OVER (PARTITION BY depname, salary) = 1;
+ depname | empno | salary | enroll_date | count
+-----------+-------+--------+-------------+-------
+ develop | 7 | 4200 | 01-01-2008 | 1
+ develop | 9 | 4500 | 01-01-2008 | 1
+ develop | 8 | 6000 | 10-01-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 1
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ sales | 1 | 5000 | 10-01-2006 | 1
+(6 rows)
+
+SELECT *,
+ RANK() OVER (ORDER BY salary DESC) as rank
+FROM empsalary
+QUALIFY rank = 2;
+ depname | empno | salary | enroll_date | rank
+---------+-------+--------+-------------+------
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 2
+(2 rows)
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date) <= 3;
+ depname | empno | salary | enroll_date | row_number
+-----------+-------+--------+-------------+------------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 3
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+ sales | 3 | 4800 | 08-01-2007 | 2
+ sales | 4 | 4800 | 08-08-2007 | 3
+(8 rows)
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC;
+ depname | empno | salary | enroll_date | row_number
+-----------+-------+--------+-------------+------------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ develop | 10 | 5200 | 08-01-2007 | 2
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+ sales | 4 | 4800 | 08-08-2007 | 2
+(6 rows)
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ AND enroll_date > DATE '2007-01-01';
+ depname | empno | salary | enroll_date | rank
+-----------+-------+--------+-------------+------
+ develop | 10 | 5200 | 08-01-2007 | 2
+ develop | 11 | 5200 | 08-15-2007 | 2
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 4 | 4800 | 08-08-2007 | 2
+ sales | 3 | 4800 | 08-01-2007 | 2
+(5 rows)
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ OR salary < 4000;
+ depname | empno | salary | enroll_date | rank
+-----------+-------+--------+-------------+------
+ develop | 8 | 6000 | 10-01-2006 | 1
+ personnel | 2 | 3900 | 12-23-2006 | 1
+ personnel | 5 | 3500 | 12-10-2007 | 2
+ sales | 1 | 5000 | 10-01-2006 | 1
+(4 rows)
+
-- cleanup
DROP TABLE empsalary;
-- test user-defined window function with named args and default args
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index 02f105f070e..4f376d1b459 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -1522,6 +1522,57 @@ SELECT * FROM
FROM empsalary) emp
WHERE first_emp = 1 OR last_emp = 1;
+-- Test QUALIFY clause
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date DESC) = 1;
+
+SELECT *,
+ AVG(salary) OVER (PARTITION BY depname) AS avg_salary
+FROM empsalary
+QUALIFY salary > avg_salary;
+
+SELECT *,
+ COUNT(*) OVER (PARTITION BY depname, salary)
+FROM empsalary
+QUALIFY COUNT(*) OVER (PARTITION BY depname, salary) = 1;
+
+SELECT *,
+ RANK() OVER (ORDER BY salary DESC) as rank
+FROM empsalary
+QUALIFY rank = 2;
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY enroll_date) <= 3;
+
+SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY ROW_NUMBER() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC;
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ AND enroll_date > DATE '2007-01-01';
+
+SELECT *,
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY
+ RANK() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ OR salary < 4000;
+
-- cleanup
DROP TABLE empsalary;
--
2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-21 22:11 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 22:56 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-25 12:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 4 replies; 41+ messages in thread
From: Vik Fearing @ 2025-07-21 22:11 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
On 21/07/2025 23:29, Matheus Alcantara wrote:
> On Mon Jul 21, 2025 at 5:23 PM -03, Vik Fearing wrote:
>> On 21/07/2025 14:47, Matheus Alcantara wrote:
>>> Hi all,
>>>
>>> I'm sending a proof-of-concept patch to add support for the QUALIFY
>>> clause in Postgres. This feature allows filtering rows after window
>>> functions are computed, using a syntax similar to the WHERE or HAVING
>>> clauses.
>>
>> I took a very brief look at this, and I think your grammar is wrong.
>> The QUALIFY clause should go after the WINDOW clause, just like
>> FROM/WHERE and GROUP BY/HAVING.
>>
>>
>> That is what I am proposing to the standards committee, and I already
>> have some buy-in for that.
>>
> Thank you for the brief review and for the comments!
>
> I'm not sure if I fully understand but please see the new attached
> version.
That is my preferred grammar, thank you. I have not looked at the C
code by this can be obtained with a syntax transformation. To wit:
SELECT a, b, c
FROM tab
QUALIFY wf() OVER () = ?
can be rewritten as:
SELECT a, b, c
FROM (
SELECT a, b, c, wf() OVER () = ? AS qc
FROM tab
) AS q
WHERE qc
and then let the optimizer take over. The standard does this kind of
thing all over the place; I don't know what the postgres project's
position on doing things like this are.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-21 22:56 ` Tom Lane <tgl@sss.pgh.pa.us>
3 siblings, 0 replies; 41+ messages in thread
From: Tom Lane @ 2025-07-21 22:56 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; +Cc: Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
Vik Fearing <vik@postgresfriends.org> writes:
> That is my preferred grammar, thank you. I have not looked at the C
> code by this can be obtained with a syntax transformation. To wit:
> SELECT a, b, c
> FROM tab
> QUALIFY wf() OVER () = ?
> can be rewritten as:
> SELECT a, b, c
> FROM (
> SELECT a, b, c, wf() OVER () = ? AS qc
> FROM tab
> ) AS q
> WHERE qc
That answers another question I was going to raise. Matheus's
opening example was
SELECT depname,
empno,
salary,
RANK() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
FROM empsalary
QUALIFY rnk = 1;
which implies that the QUALIFY clause sees the SELECT output columns,
and hence that it can't use any values not emitted by the SELECT list.
Your transformation implies that it sees the same namespace as the
SELECT list, which seems like a much better and less confusing
definition to me.
regards, tom lane
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-22 03:19 ` Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
3 siblings, 1 reply; 41+ messages in thread
From: Pavel Stehule @ 2025-07-22 03:19 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; +Cc: Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
Hi
út 22. 7. 2025 v 0:12 odesílatel Vik Fearing <vik@postgresfriends.org>
napsal:
>
> On 21/07/2025 23:29, Matheus Alcantara wrote:
> > On Mon Jul 21, 2025 at 5:23 PM -03, Vik Fearing wrote:
> >> On 21/07/2025 14:47, Matheus Alcantara wrote:
> >>> Hi all,
> >>>
> >>> I'm sending a proof-of-concept patch to add support for the QUALIFY
> >>> clause in Postgres. This feature allows filtering rows after window
> >>> functions are computed, using a syntax similar to the WHERE or HAVING
> >>> clauses.
> >>
> >> I took a very brief look at this, and I think your grammar is wrong.
> >> The QUALIFY clause should go after the WINDOW clause, just like
> >> FROM/WHERE and GROUP BY/HAVING.
> >>
> >>
> >> That is what I am proposing to the standards committee, and I already
> >> have some buy-in for that.
> >>
> > Thank you for the brief review and for the comments!
> >
> > I'm not sure if I fully understand but please see the new attached
> > version.
>
>
> That is my preferred grammar, thank you. I have not looked at the C
> code by this can be obtained with a syntax transformation. To wit:
>
>
> SELECT a, b, c
> FROM tab
> QUALIFY wf() OVER () = ?
>
>
> can be rewritten as:
>
>
> SELECT a, b, c
> FROM (
> SELECT a, b, c, wf() OVER () = ? AS qc
> FROM tab
> ) AS q
> WHERE qc
>
>
> and then let the optimizer take over. The standard does this kind of
> thing all over the place; I don't know what the postgres project's
> position on doing things like this are.
>
just for curiosity - why the HAVING clause was not used?
Any window functions are +/- an "aggregate" function, and then HAVING looks
more natural to me.
Regards
Pavel
> --
>
> Vik Fearing
>
>
>
>
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
@ 2025-07-22 03:43 ` Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
0 siblings, 1 reply; 41+ messages in thread
From: Merlin Moncure @ 2025-07-22 03:43 UTC (permalink / raw)
To: Pavel Stehule <pavel.stehule@gmail.com>; +Cc: Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, Jul 21, 2025 at 9:19 PM Pavel Stehule <pavel.stehule@gmail.com>
wrote:
>
> just for curiosity - why the HAVING clause was not used?
>
> Any window functions are +/- an "aggregate" function, and then HAVING
> looks more natural to me.
>
Hm, HAVING requires to apply 'group by' which windows functions do not
require (unlike aggregates).
superuser@postgres=# select * from (select 1 as v) q having true limit 1;
ERROR: column "q.v" must appear in the GROUP BY clause or be used in an
aggregate function
LINE 1: select * from (select 1 as v) q having true limit 1;
If a query has both window function and grouped aggregate, HAVING would be
applying at different grains potentially? If so, seems sus.
merlin
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
@ 2025-07-22 04:08 ` Nico Williams <nico@cryptonector.com>
2025-07-22 05:02 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 05:14 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 2 replies; 41+ messages in thread
From: Nico Williams @ 2025-07-22 04:08 UTC (permalink / raw)
To: Merlin Moncure <mmoncure@gmail.com>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, Jul 21, 2025 at 09:43:15PM -0600, Merlin Moncure wrote:
> On Mon, Jul 21, 2025 at 9:19 PM Pavel Stehule <pavel.stehule@gmail.com>
> wrote:
> > just for curiosity - why the HAVING clause was not used?
> >
> > Any window functions are +/- an "aggregate" function, and then HAVING
> > looks more natural to me.
>
> Hm, HAVING requires to apply 'group by' which windows functions do not
> require (unlike aggregates).
Pavel's point is precisely to allow HAVING w/o a GROUP BY when there are
window functions since window functions are "+/-" ("more or less")
aggregate functions. That makes sense to me.
> superuser@postgres=# select * from (select 1 as v) q having true limit 1;
> ERROR: column "q.v" must appear in the GROUP BY clause or be used in an
> aggregate function
> LINE 1: select * from (select 1 as v) q having true limit 1;
>
> If a query has both window function and grouped aggregate, HAVING would be
> applying at different grains potentially? If so, seems sus.
I would have a HAVING clause that comes _before_ GROUP BY apply to
window functions and a second one that comes _after_ GROUP BY apply to
the grouping.
Nico
--
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
@ 2025-07-22 05:02 ` Merlin Moncure <mmoncure@gmail.com>
2025-07-22 15:04 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 15:14 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
1 sibling, 2 replies; 41+ messages in thread
From: Merlin Moncure @ 2025-07-22 05:02 UTC (permalink / raw)
To: Nico Williams <nico@cryptonector.com>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, Jul 21, 2025 at 10:08 PM Nico Williams <nico@cryptonector.com>
wrote:
> On Mon, Jul 21, 2025 at 09:43:15PM -0600, Merlin Moncure wrote:
> > On Mon, Jul 21, 2025 at 9:19 PM Pavel Stehule <pavel.stehule@gmail.com>
> > wrote:
> > > just for curiosity - why the HAVING clause was not used?
> > >
> > > Any window functions are +/- an "aggregate" function, and then HAVING
> > > looks more natural to me.
> >
> > Hm, HAVING requires to apply 'group by' which windows functions do not
> > require (unlike aggregates).
>
> Pavel's point is precisely to allow HAVING w/o a GROUP BY when there are
> window functions since window functions are "+/-" ("more or less")
> aggregate functions. That makes sense to me.
>
> > superuser@postgres=# select * from (select 1 as v) q having true limit
> 1;
> > ERROR: column "q.v" must appear in the GROUP BY clause or be used in an
> > aggregate function
> > LINE 1: select * from (select 1 as v) q having true limit 1;
> >
> > If a query has both window function and grouped aggregate, HAVING would
> be
> > applying at different grains potentially? If so, seems sus.
>
> I would have a HAVING clause that comes _before_ GROUP BY apply to
> window functions and a second one that comes _after_ GROUP BY apply to
> the grouping.
>
I don't know...consider:
#1 SELECT lag(1) OVER(), max(v) FROM (SELECT 1 AS v) q HAVING true ;
...
#2 SELECT lag(1) OVER(), max(v) FROM (SELECT 1 AS v) q HAVING true HAVING
lag(1) OVER() IS NULL;
What does the HAVING clause apply to in #1? I think you might be in
trouble with the standard here. 2nd clause doesn't feel right in #2. The
basic problem is that HAVING does more than just 'syntax sugar subquery /
WHERE' and it just can't be hijacked to do something else IMO.
Syntax simplifying
SELECT * FROM (<window function query>) WHERE col = x
Does have some merit, but implementing non-standard syntax has risks,
especially in this area of the grammar. If you did do it, I'd vote for
QUALIFY since implementation consensus seems to influence the standard to
some degree, but I have to unfortunately +1 the 'reserved word' warning.
You could probably work around that with more complex syntax but that kind
of defeats the point.
merlin
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:02 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
@ 2025-07-22 15:04 ` Nico Williams <nico@cryptonector.com>
1 sibling, 0 replies; 41+ messages in thread
From: Nico Williams @ 2025-07-22 15:04 UTC (permalink / raw)
To: Merlin Moncure <mmoncure@gmail.com>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Mon, Jul 21, 2025 at 11:02:36PM -0600, Merlin Moncure wrote:
> On Mon, Jul 21, 2025 at 10:08 PM Nico Williams <nico@cryptonector.com>
> wrote:
> > I would have a HAVING clause that comes _before_ GROUP BY apply to
> > window functions and a second one that comes _after_ GROUP BY apply to
> > the grouping.
>
> I don't know...consider:
> #1 SELECT lag(1) OVER(), max(v) FROM (SELECT 1 AS v) q HAVING true ;
> ...
> #2 SELECT lag(1) OVER(), max(v) FROM (SELECT 1 AS v) q HAVING true HAVING
> lag(1) OVER() IS NULL;
>
> What does the HAVING clause apply to in #1? I think you might be in
> trouble with the standard here. 2nd clause doesn't feel right in #2. The
> basic problem is that HAVING does more than just 'syntax sugar subquery /
> WHERE' and it just can't be hijacked to do something else IMO.
#2 would be a syntax error because the second HAVING did not come after
a GROUP BY. #1 would not be a syntax error only because of the use of
window functions before the HAVING.
> Syntax simplifying
> SELECT * FROM (<window function query>) WHERE col = x
Yes. I'd rather that than QUALIFY. QUALIFY only makes sense because so
many other RDBMSes have it and it's likely to get standardized.
Nico
--
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:02 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
@ 2025-07-22 15:14 ` Nico Williams <nico@cryptonector.com>
2025-07-22 15:24 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
1 sibling, 1 reply; 41+ messages in thread
From: Nico Williams @ 2025-07-22 15:14 UTC (permalink / raw)
To: Merlin Moncure <mmoncure@gmail.com>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
I often accidentally write
SELECT .. WHERE .. WHERE ..;
which is obviously wrong, but what I mean when I do this is
SELECT .. WHERE .. AND ..;
and if I wrote GROUP BY .. HAVING queries as often as I do ones that
don't GROUP BY then I'd probably also accidentally use extra HAVINGs as
ANDs.
It doesn't seem too crazy that extra WHEREs in WHERE clauses should some
day function as ANDs, and ditto HAVINGs, which is another reason not to
reuse HAVING for this: just to leave that a possibility, remote though
it might be.
My advice is to wait till QUALIFY is standardized, then hold your nose
and adopt it, or maybe sooner when it becomes clear that it will be
standardized (because so many other RDBMSes have it too).
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:02 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 15:14 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
@ 2025-07-22 15:24 ` Vik Fearing <vik@postgresfriends.org>
0 siblings, 0 replies; 41+ messages in thread
From: Vik Fearing @ 2025-07-22 15:24 UTC (permalink / raw)
To: Nico Williams <nico@cryptonector.com>; Merlin Moncure <mmoncure@gmail.com>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 22/07/2025 17:14, Nico Williams wrote:
> It doesn't seem too crazy that extra WHEREs in WHERE clauses should some
> day function as ANDs, and ditto HAVINGs, which is another reason not to
> reuse HAVING for this: just to leave that a possibility, remote though
> it might be.
I have a firm finger on the pulse of the standards committee, and I can
guarantee that multiple WHERE clauses will never replace AND until
certain people cross the river Styx. Myself included.
> My advice is to wait till QUALIFY is standardized, then hold your nose
> and adopt it, or maybe sooner when it becomes clear that it will be
> standardized (because so many other RDBMSes have it too).
Good advice.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
@ 2025-07-22 05:14 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 15:07 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
1 sibling, 1 reply; 41+ messages in thread
From: Tom Lane @ 2025-07-22 05:14 UTC (permalink / raw)
To: Nico Williams <nico@cryptonector.com>; +Cc: Merlin Moncure <mmoncure@gmail.com>; Pavel Stehule <pavel.stehule@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
Nico Williams <nico@cryptonector.com> writes:
> On Mon, Jul 21, 2025 at 09:43:15PM -0600, Merlin Moncure wrote:
>> Hm, HAVING requires to apply 'group by' which windows functions do not
>> require (unlike aggregates).
> Pavel's point is precisely to allow HAVING w/o a GROUP BY when there are
> window functions since window functions are "+/-" ("more or less")
> aggregate functions. That makes sense to me.
No, it's really quite wrong. Aggregate functions are not equivalent
to window functions: if you have both in a query, they execute in
separate passes, with the window functions operating on the grouped
rows output by the aggregation step (and then filtered by HAVING,
if any).
If we're going to support this, it does need to be its own clause.
regards, tom lane
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:14 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
@ 2025-07-22 15:07 ` Nico Williams <nico@cryptonector.com>
2025-07-22 15:14 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
0 siblings, 1 reply; 41+ messages in thread
From: Nico Williams @ 2025-07-22 15:07 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Merlin Moncure <mmoncure@gmail.com>; Pavel Stehule <pavel.stehule@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Tue, Jul 22, 2025 at 01:14:20AM -0400, Tom Lane wrote:
> Nico Williams <nico@cryptonector.com> writes:
> > On Mon, Jul 21, 2025 at 09:43:15PM -0600, Merlin Moncure wrote:
> >> Hm, HAVING requires to apply 'group by' which windows functions do not
> >> require (unlike aggregates).
>
> > Pavel's point is precisely to allow HAVING w/o a GROUP BY when there are
> > window functions since window functions are "+/-" ("more or less")
> > aggregate functions. That makes sense to me.
>
> No, it's really quite wrong. Aggregate functions are not equivalent
> to window functions: if you have both in a query, they execute in
> separate passes, with the window functions operating on the grouped
> rows output by the aggregation step (and then filtered by HAVING,
> if any).
Pavel doesn't say that window functions are aggregate functions. Pavel
said they are +/- (more or less, really, just similar to) aggregate
functions. There is a similarity. But I appreciate the point about
which passes get which, and that definitely makes the two-HAVING-
clauses concept much more unwieldy.
> If we're going to support this, it does need to be its own clause.
I agree that its own clause is best; I just greatly dislike QUALIFY.
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:14 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 15:07 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
@ 2025-07-22 15:14 ` Vik Fearing <vik@postgresfriends.org>
2025-07-22 15:26 ` Re: Proposal: QUALIFY clause Andrew Dunstan <andrew@dunslane.net>
0 siblings, 1 reply; 41+ messages in thread
From: Vik Fearing @ 2025-07-22 15:14 UTC (permalink / raw)
To: Nico Williams <nico@cryptonector.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Merlin Moncure <mmoncure@gmail.com>; Pavel Stehule <pavel.stehule@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 22/07/2025 17:07, Nico Williams wrote:
> On Tue, Jul 22, 2025 at 01:14:20AM -0400, Tom Lane wrote:
>> Nico Williams <nico@cryptonector.com> writes:
>>> On Mon, Jul 21, 2025 at 09:43:15PM -0600, Merlin Moncure wrote:
>>>> Hm, HAVING requires to apply 'group by' which windows functions do not
>>>> require (unlike aggregates).
>>> Pavel's point is precisely to allow HAVING w/o a GROUP BY when there are
>>> window functions since window functions are "+/-" ("more or less")
>>> aggregate functions. That makes sense to me.
>> No, it's really quite wrong. Aggregate functions are not equivalent
>> to window functions: if you have both in a query, they execute in
>> separate passes, with the window functions operating on the grouped
>> rows output by the aggregation step (and then filtered by HAVING,
>> if any).
> Pavel doesn't say that window functions are aggregate functions. Pavel
> said they are +/- (more or less, really, just similar to) aggregate
> functions. There is a similarity. But I appreciate the point about
> which passes get which, and that definitely makes the two-HAVING-
> clauses concept much more unwieldy.
Window functions and aggregates have only one thing in common, and that
is that they can both operate on a window frame. Otherwise the
difference is night and day. Especially when you consider nested window
clauses (that postgres does not support yet).
> I agree that its own clause is best; I just greatly dislike QUALIFY.
Sorry.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:14 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 15:07 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 15:14 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-22 15:26 ` Andrew Dunstan <andrew@dunslane.net>
2025-07-23 08:12 ` Re: Proposal: QUALIFY clause Álvaro Herrera <alvherre@kurilemu.de>
0 siblings, 1 reply; 41+ messages in thread
From: Andrew Dunstan @ 2025-07-22 15:26 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; Nico Williams <nico@cryptonector.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Merlin Moncure <mmoncure@gmail.com>; Pavel Stehule <pavel.stehule@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 2025-07-22 Tu 11:14 AM, Vik Fearing wrote:
>
>
>> I agree that its own clause is best; I just greatly dislike QUALIFY.
>
>
> Sorry.
>
If we were making up our own syntax this would be a sensible thing to
debate. If we're talking about implementing something we expect to be in
the standard, I think we will have to live with what the standards
committee decides, regardless of our preference. We've almost certainly
been preempted here by other RDBMSs using QUALIFY, heedless of English
grammar.
cheers
andrew
--
Andrew Dunstan
EDB: https://www.enterprisedb.com
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 03:19 ` Re: Proposal: QUALIFY clause Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Re: Proposal: QUALIFY clause Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 05:14 ` Re: Proposal: QUALIFY clause Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 15:07 ` Re: Proposal: QUALIFY clause Nico Williams <nico@cryptonector.com>
2025-07-22 15:14 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 15:26 ` Re: Proposal: QUALIFY clause Andrew Dunstan <andrew@dunslane.net>
@ 2025-07-23 08:12 ` Álvaro Herrera <alvherre@kurilemu.de>
0 siblings, 0 replies; 41+ messages in thread
From: Álvaro Herrera @ 2025-07-23 08:12 UTC (permalink / raw)
To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Vik Fearing <vik@postgresfriends.org>; Nico Williams <nico@cryptonector.com>; Tom Lane <tgl@sss.pgh.pa.us>; Merlin Moncure <mmoncure@gmail.com>; Pavel Stehule <pavel.stehule@gmail.com>; Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 2025-Jul-22, Andrew Dunstan wrote:
> If we were making up our own syntax this would be a sensible thing to
> debate. If we're talking about implementing something we expect to be in the
> standard, I think we will have to live with what the standards committee
> decides, regardless of our preference. We've almost certainly been preempted
> here by other RDBMSs using QUALIFY, heedless of English grammar.
The Romans, the Vikings, the Normans, all have influenced the English
language. Why not SQL?
--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
“Cuando no hay humildad las personas se degradan” (A. Christie)
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-22 11:55 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
3 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-22 11:55 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
On Mon Jul 21, 2025 at 7:11 PM -03, Vik Fearing wrote:
> That is my preferred grammar, thank you.
>
Thanks for confirming!
> I have not looked at the C code by this can be obtained with a syntax
> transformation. To wit:
> SELECT a, b, c
> FROM tab
> QUALIFY wf() OVER () = ?
>
>
> can be rewritten as:
>
>
> SELECT a, b, c
> FROM (
> SELECT a, b, c, wf() OVER () = ? AS qc
> FROM tab
> ) AS q
> WHERE qc
>
>
> and then let the optimizer take over. The standard does this kind of
> thing all over the place; I don't know what the postgres project's
> position on doing things like this are.
>
The current patch supports the following syntaxes:
SELECT a, b, c
wf() OVER () as d
FROM tab
QUALIFY d = 1
and
SELECT a, b, c
wf() OVER ()
FROM tab
QUALIFY wf() OVER () = 1
When using the "QUALIFY d = 1" form, I currently rewrite the expression
as "wf() OVER () = 1" by searching the targetlist for the matching
alias, replacing the Var with the corresponding WindowFunc. Then I
append this clause to the topqual, which is later assigned to
WindowAggPath.plan->qual in create_one_window_path().
Besides this approach works I'm almost sure that this is not correct
because searching the window function on targetlist doesen't seems
correct to me. Tom also pointed out that this design could be confusing,
which reinforces the need to rethink it.
This transformation that you've suggested seems a better approach to
handle the QUALIFY clause to me as well. Unless anyone objects, I'll
prepare the next patch version based on that strategy.
Thanks very much for the comments!
--
Matheus Alcantara
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-22 18:11 ` Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: Marcos Pegoraro @ 2025-07-22 18:11 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
Em ter., 22 de jul. de 2025 às 08:56, Matheus Alcantara <
matheusssilv97@gmail.com> escreveu:
> The current patch supports the following syntaxes:
> SELECT a, b, c
> wf() OVER () as d
> FROM tab
> QUALIFY d = 1
> When using the "QUALIFY d = 1" form, I currently rewrite the expression
> as "wf() OVER () = 1" by searching the targetlist for the matching
> alias, replacing the Var with the corresponding WindowFunc.
>
Not related to $subject but that way you did,
that replacement alias for wf expression, is cool.
With that would it be possible to have where replacements too ? Maybe.
select a+b as ab from t where ab = 5
regards
Marcos
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
@ 2025-07-22 18:54 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
0 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-22 18:54 UTC (permalink / raw)
To: Marcos Pegoraro <marcos@f10.com.br>; +Cc: Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Tue Jul 22, 2025 at 3:11 PM -03, Marcos Pegoraro wrote:
> Em ter., 22 de jul. de 2025 às 08:56, Matheus Alcantara <
> matheusssilv97@gmail.com> escreveu:
>
>> The current patch supports the following syntaxes:
>> SELECT a, b, c
>> wf() OVER () as d
>> FROM tab
>> QUALIFY d = 1
>> When using the "QUALIFY d = 1" form, I currently rewrite the expression
>> as "wf() OVER () = 1" by searching the targetlist for the matching
>> alias, replacing the Var with the corresponding WindowFunc.
>>
>
> Not related to $subject but that way you did,
> that replacement alias for wf expression, is cool.
> With that would it be possible to have where replacements too ? Maybe.
>
> select a+b as ab from t where ab = 5
>
Do you mean instead of reference the "ab" using a Var it replaces with a
OpExpr of "a+b"? I think that it would be possible, but the current
implementation is not fully correct, it only works for OpExpr's. Using
AND/OR operators does not work and I think that to make it fully correct
is more complex, so I think that rewriting the query to use a subquery
as Vik suggested on [1] fixes this issue and also makes it easier to
understand.
(this happens on transformQualifyClause() if you want to take a look)
[1] https://www.postgresql.org/message-id/6c998e4f-f6f2-43c2-8b67-cfff360ef241%40postgresfriends.org
--
Matheus Alcantara
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-22 21:21 ` Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: Vik Fearing @ 2025-07-22 21:21 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; Marcos Pegoraro <marcos@f10.com.br>; +Cc: pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 22/07/2025 20:54, Matheus Alcantara wrote:
> (this happens on transformQualifyClause() if you want to take a look)
I took a quick look at the patch (without applying and testing it) and
it seems to me that parse analysis is the wrong place to do this. We
want ruleutils to be able to spew out the QUALIFY clause as written in a
view and not as transformed. If we are going to go down the syntax
transformation route, that should happen in the rewriter at
planning/execution time.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-22 22:32 ` David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: David Rowley @ 2025-07-22 22:32 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; +Cc: Matheus Alcantara <matheusssilv97@gmail.com>; Marcos Pegoraro <marcos@f10.com.br>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Wed, 23 Jul 2025 at 09:21, Vik Fearing <vik@postgresfriends.org> wrote:
> I took a quick look at the patch (without applying and testing it) and
> it seems to me that parse analysis is the wrong place to do this. We
> want ruleutils to be able to spew out the QUALIFY clause as written in a
> view and not as transformed. If we are going to go down the syntax
> transformation route, that should happen in the rewriter at
> planning/execution time.
I agree with Tom on not jumping the gun on the standard thing, but if
that does materialise one day, then whichever method is used, you'd
still want the same pushdown optimisations to happen that currently
happen with qual pushdown into subqueries.
Looking at the latest patch I see that pushdowns don't work:
# explain select row_number() over (order by oid) rb from pg_Class
qualify row_number () over (order by oid)=1;
# explain (analyze, costs off, buffers off, summary off) select
row_number() over (order by oid) rb from pg_Class qualify row_number
() over (order by oid)=1;
WindowAgg (actual time=0.041..0.273 rows=1.00 loops=1)
Window: w1 AS (ORDER BY oid ROWS UNBOUNDED PRECEDING)
Filter: (row_number() OVER w1 = 1)
Rows Removed by Filter: 415
Storage: Memory Maximum Storage: 17kB
-> Index Only Scan using pg_class_oid_index on pg_class (actual
time=0.032..0.125 rows=416.00 loops=1)
Heap Fetches: 0
Index Searches: 1
Whereas, with a subquery we get:
# explain (analyze, costs off, buffers off, summary off)
select * from (select row_number() over (order by oid) rn from
pg_class) r where r.rn=1;
Subquery Scan on r (actual time=0.042..0.044 rows=1.00 loops=1)
Filter: (r.rn = 1)
-> WindowAgg (actual time=0.041..0.043 rows=1.00 loops=1)
Window: w1 AS (ORDER BY pg_class.oid ROWS UNBOUNDED PRECEDING)
Run Condition: (row_number() OVER w1 <= 1)
Storage: Memory Maximum Storage: 17kB
-> Index Only Scan using pg_class_oid_index on pg_class
(actual time=0.030..0.031 rows=2.00 loops=1)
Heap Fetches: 0
Index Searches: 1
Also, this seems busted:
# select row_number() over (order by oid) rn from pg_class qualify rn=1;
server closed the connection unexpectedly
David
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
@ 2025-07-29 00:10 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-29 00:46 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-29 00:10 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; Vik Fearing <vik@postgresfriends.org>; +Cc: Marcos Pegoraro <marcos@f10.com.br>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On 22/07/25 19:32, David Rowley wrote:
> Looking at the latest patch I see that pushdowns don't work:
>
> # explain select row_number() over (order by oid) rb from pg_Class
> qualify row_number () over (order by oid)=1;
>
> # explain (analyze, costs off, buffers off, summary off) select
> row_number() over (order by oid) rb from pg_Class qualify row_number
> () over (order by oid)=1;
>
> WindowAgg (actual time=0.041..0.273 rows=1.00 loops=1)
> Window: w1 AS (ORDER BY oid ROWS UNBOUNDED PRECEDING)
> Filter: (row_number() OVER w1 = 1)
> Rows Removed by Filter: 415
> Storage: Memory Maximum Storage: 17kB
> -> Index Only Scan using pg_class_oid_index on pg_class (actual
> time=0.032..0.125 rows=416.00 loops=1)
> Heap Fetches: 0
> Index Searches: 1
>
> Whereas, with a subquery we get:
>
> # explain (analyze, costs off, buffers off, summary off)
> select * from (select row_number() over (order by oid) rn from
> pg_class) r where r.rn=1;
>
> Subquery Scan on r (actual time=0.042..0.044 rows=1.00 loops=1)
> Filter: (r.rn = 1)
> -> WindowAgg (actual time=0.041..0.043 rows=1.00 loops=1)
> Window: w1 AS (ORDER BY pg_class.oid ROWS UNBOUNDED PRECEDING)
> Run Condition: (row_number() OVER w1 <= 1)
> Storage: Memory Maximum Storage: 17kB
> -> Index Only Scan using pg_class_oid_index on pg_class
> (actual time=0.030..0.031 rows=2.00 loops=1)
> Heap Fetches: 0
> Index Searches: 1
>
By "pushdowns" you mean missing the Run Conditions on the QUALIFY
example? IIUC the Run Condition is only created if it's a subquery. I've
checked this on set_rel_size() -> set_subquery_pathlist() ->
check_and_push_window_quals().
> Also, this seems busted:
>
> # select row_number() over (order by oid) rn from pg_class qualify rn=1;
> server closed the connection unexpectedly
>
Thanks for testing! I'm working on this and some other issues.
--
Matheus Alcantara
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-29 00:46 ` David Rowley <dgrowleyml@gmail.com>
2025-07-29 09:48 ` Re: Proposal: QUALIFY clause Richard Guo <guofenglinux@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: David Rowley @ 2025-07-29 00:46 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; +Cc: Vik Fearing <vik@postgresfriends.org>; Marcos Pegoraro <marcos@f10.com.br>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Tue, 29 Jul 2025 at 12:11, Matheus Alcantara
<matheusssilv97@gmail.com> wrote:
> By "pushdowns" you mean missing the Run Conditions on the QUALIFY
> example? IIUC the Run Condition is only created if it's a subquery. I've
> checked this on set_rel_size() -> set_subquery_pathlist() ->
> check_and_push_window_quals().
Yes, but not only Run Conditions, it's subquery pushdown quals in
general. There are various rules to what is allowed and what must be
disallowed. See check_output_expressions().
You should be pushing the qual to the lowest level that it's valid to
evaluate it at. We do this already for HAVING quals where those will
effectively be "transferred" to the WHERE clause when it's valid to do
so. I'd expect the same for QUALIFY. I'm unsure which parts of
subquery pushdown could be made more reusable to help you with this.
Ideally we'd not have to duplicate lots of logic in various places. If
you do manage to get around the whole SQL standard issue around
QUALIFY, then a large portion of a patch like this being acceptable
will largely depend on how much code gets reused vs how much you have
to rewrite from scratch. It's not that fun to have to duplicate logic
in multiple places when new optimisations are added. See d222585a9 for
an example of an optimisation that would likely have to be duplicated
if QUALIFY existed.
David
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-29 00:46 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
@ 2025-07-29 09:48 ` Richard Guo <guofenglinux@gmail.com>
2026-06-29 14:41 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: Richard Guo @ 2025-07-29 09:48 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; +Cc: Matheus Alcantara <matheusssilv97@gmail.com>; Vik Fearing <vik@postgresfriends.org>; Marcos Pegoraro <marcos@f10.com.br>; pgsql-hackers; Peter Eisentraut <peter@eisentraut.org>
On Tue, Jul 29, 2025 at 9:47 AM David Rowley <dgrowleyml@gmail.com> wrote:
> You should be pushing the qual to the lowest level that it's valid to
> evaluate it at. We do this already for HAVING quals where those will
> effectively be "transferred" to the WHERE clause when it's valid to do
> so. I'd expect the same for QUALIFY.
Yeah, we should have the same kind of optimization for a QUALIFY
clause as we do for HAVING - pushing it down to WHERE when possible.
One condition for doing this is that the QUALIFY clause does not
reference any columns that are not present in the window PARTITION BY
clauses. There may be other conditions under which we can have
other optimizations, such as pushing down a QUALIFY clause as run
conditions.
I think we should at a minimum inherit all existing optimizations for
window functions used in subqueries; otherwise, it will be difficult
to convince others to accept this patch.
Thanks
Richard
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-29 00:46 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 09:48 ` Re: Proposal: QUALIFY clause Richard Guo <guofenglinux@gmail.com>
@ 2026-06-29 14:41 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-07-14 18:23 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2026-06-29 14:41 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Vik Fearing <vik@postgresfriends.org>; Marcos Pegoraro <marcos@f10.com.br>; Peter Eisentraut <peter@eisentraut.org>; Richard Guo <guofenglinux@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>
Hi all,
It's been a while, but I'd like to revisit this thread now that the
QUALIFY proposal has been accepted by the SQL standard, so I'd like to
pick the work back up.
TLDR: QUALIFY clause is a general post select filter and it can be used
to filters rows on the result of a window function without wrapping the
query in a subquery or CTE. It is to window functions what HAVING is to
aggregates — a post-SELECT filter, evaluated after the window functions
are computed but before DISTINCT/ORDER BY/LIMIT. Note that QUALIFY
clause does not require a window function to be defined, it is a general
post select filter so it also allow to filter rows based on computed
column alias.
The attached patch include documentation and regression tests that
implement the expected behavior as defined by the accepted standard
proposal.
Implementation:
The standard defines QUALIFY by a syntactic transformation into a
subquery, and the attached patch implements exactly that, as a query
rewrite performed after parse analysis (in analyze.c): the table
expression and select list become an inner subquery, and the QUALIFY
condition becomes the WHERE clause of an outer query, with ORDER
BY/DISTINCT/LIMIT lifted to that outer query.
I first tried doing this rewrite before parse analysis, by building the
nested SelectStmt and letting normal analysis take over. That doesn't
work, for two reasons:
- The QUALIFY condition has to be resolved in the scope of the table
expression. With a pre-analysis rewrite it becomes the outer query's
WHERE, where only the subquery's output columns are visible. So a
QUALIFY reference to a non-selected table column can't be resolved at
all, and the alias-vs-column precedence inverts (the alias would win,
contrary to the standard).
- A window function in QUALIFY would land in the outer WHERE, which is
illegal — window functions aren't allowed there. To be legal it must
be computed in the subquery and referenced from outside, but
identifying the window functions (and aggregates, and which columns to
project) requires the analyzed tree. So the rewrite has to happen
after analysis.
The big win of the rewrite approach is that the planner already
optimizes window functions sitting inside a subquery, so QUALIFY gets
those optimizations (window run conditions and pushing quals down below
the WindowAgg) for free, with no new planner code. The plans come out
identical to the equivalent hand-written subquery.
The main downside is view deparse: because the stored query is the
rewritten subquery, pg_get_viewdef() of a view defined with QUALIFY
shows the subquery form rather than the QUALIFY keyword.
An alternative:
Another approach is to teach the planner about QUALIFY directly and
apply the same window optimizations to its quals. I'm attaching a second
patch (v2-0001-Add-QUALIFY-clause.patch.nocfbot) that does this, but
only for the window-function case. Since QUALIFY is a general
post-SELECT filter, a condition that doesn't reference a window function
would, in this approach, need a gating Result node carrying the QUALIFY
filter on top of the plan tree; that part is not implemented in this
patch. This approach keeps QUALIFY first-class (clean view deparse, no
synthetic subquery), at the cost of duplicating the run-condition and
qual-pushdown logic that today lives at the subquery boundary.
So there are two patches attached:
- v2-0001-Add-QUALIFY-clause.patch: the query-rewrite approach, complete (window and
non-window QUALIFY), with docs and tests.
- v2-0001-Add-QUALIFY-clause.patch.nocfbot: the planner-based approach,
window-functions only. Note that there is some test cases failing due
to WIP state.
Open question:
I'm not sure which architecture is the right long-term direction, and
I'd like feedback before investing further. I lean slightly toward the
planner-infrastructure approach for the cleaner representation (no
subquery wrapping, QUALIFY preserved in views), even though it currently
duplicates the run-condition and qual-pushdown code. We could refactor
find_window_run_conditions()/check_and_push_window_quals() and the
pushdown helpers to be reusable outside set_subquery_pathlist() so
QUALIFY can share them — but I'd rather hear opinions on the overall
direction first.
Thoughts on which approach to pursue would be very welcome.
Thanks
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
Attachments:
v2-0001-Add-QUALIFY-clause.patch (text/plain, 85.7K) download
From baf267b35bbfe0197a510ab9a5a3f01ee8c23c6c Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <mths.dev@pm.me>
Date: Mon, 29 Jun 2026 10:49:43 -0300
Subject: [PATCH v2] Add QUALIFY clause
QUALIFY filters rows using the result of a window function without
requiring the query to be wrapped in a subquery or CTE. It is to window
functions what HAVING is to aggregates: a post-SELECT filter, evaluated
after the window functions have been computed but before DISTINCT, ORDER
BY, and LIMIT. The condition may contain window functions directly,
whether or not they also appear in the select list, and it may reference
select-list output names, which are not visible to WHERE or HAVING.
The clause is implemented in the parser by rewriting a query
specification that carries a QUALIFY clause into an equivalent two-level
query: an inner subquery holding the table expression and select list,
wrapped by an outer query whose WHERE clause is the QUALIFY condition.
This follows the syntactic transformation described in the SQL standard
change proposal. Because the planner already optimizes window functions
that appear inside a subquery, the rewritten form obtains window run
conditions and quals pushdown without any new planner code, producing
plans identical to those of the equivalent hand-written subquery.
The condition is transformed in the scope of the inner query, so a name
that refers to a column of the FROM tables resolves to that column in
preference to a select-list alias of the same name. Window functions,
aggregates, and inner columns referenced by the condition are projected
through the subquery and referenced from the outer WHERE clause by Vars
nodes, which preserves the comparison shape that the run-condition
machinery recognizes. Because QUALIFY is evaluated after the select
list, the ORDER BY, DISTINCT, and LIMIT clauses are processed against
the outer query.
QUALIFY is added as a reserved keyword, as required by the standard.
---
doc/src/sgml/ref/select.sgml | 99 +++
src/backend/nodes/nodeFuncs.c | 2 +
src/backend/parser/analyze.c | 504 +++++++++++
src/backend/parser/gram.y | 16 +-
src/backend/parser/parse_agg.c | 4 +
src/backend/parser/parse_expr.c | 4 +
src/backend/parser/parse_func.c | 3 +
src/include/nodes/parsenodes.h | 1 +
src/include/parser/kwlist.h | 1 +
src/include/parser/parse_node.h | 1 +
src/test/regress/expected/qualify.out | 1122 +++++++++++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/qualify.sql | 563 +++++++++++++
src/tools/pgindent/typedefs.list | 3 +
14 files changed, 2320 insertions(+), 5 deletions(-)
create mode 100644 src/test/regress/expected/qualify.out
create mode 100644 src/test/regress/sql/qualify.sql
diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml
index 09b6ce809bb..7387dba5549 100644
--- a/doc/src/sgml/ref/select.sgml
+++ b/doc/src/sgml/ref/select.sgml
@@ -40,6 +40,7 @@ SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replac
[ GROUP BY { ALL | [ ALL | DISTINCT ] <replaceable class="parameter">grouping_element</replaceable> [, ...] } ]
[ HAVING <replaceable class="parameter">condition</replaceable> ]
[ WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] ]
+ [ QUALIFY <replaceable class="parameter">condition</replaceable> ]
[ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class="parameter">select</replaceable> ]
[ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]
[ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ]
@@ -146,6 +147,16 @@ TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]
</para>
</listitem>
+ <listitem>
+ <para>
+ If the <literal>QUALIFY</literal> clause is specified, all rows
+ that do not satisfy the condition are eliminated from the output.
+ Because <literal>QUALIFY</literal> is applied after the output rows
+ have been computed, its condition can reference window functions
+ and output column names. (See <xref linkend="sql-qualify"/> below.)
+ </para>
+ </listitem>
+
<listitem>
<para><literal>SELECT DISTINCT</literal> eliminates duplicate rows from the
result. <literal>SELECT DISTINCT ON</literal> eliminates rows that
@@ -1242,6 +1253,83 @@ EXCLUDE NO OTHERS
</note>
</refsect2>
+ <refsect2 id="sql-qualify" xreflabel="QUALIFY Clause">
+ <title><literal>QUALIFY</literal> Clause</title>
+
+ <para>
+ The optional <literal>QUALIFY</literal> clause has the general form
+<synopsis>
+QUALIFY <replaceable class="parameter">condition</replaceable>
+</synopsis>
+ where <replaceable class="parameter">condition</replaceable> is
+ any expression that evaluates to a result of type
+ <type>boolean</type>, the same as specified for the
+ <literal>WHERE</literal> clause.
+ </para>
+
+ <para>
+ <literal>QUALIFY</literal> eliminates rows that do not satisfy the
+ condition. It is applied after window functions have been computed,
+ so its condition may refer to the results of window functions. In
+ this respect <literal>QUALIFY</literal> is to window functions what
+ <link linkend="sql-having"><literal>HAVING</literal></link> is to
+ aggregate functions: each filters the result of its corresponding
+ computation stage. Without <literal>QUALIFY</literal>, filtering on
+ the result of a window function requires wrapping the query in a
+ sub-query (or common table expression) and applying a
+ <literal>WHERE</literal> clause there, because window functions are
+ computed after <literal>WHERE</literal> and <literal>HAVING</literal>.
+ A row is retained only if the condition evaluates to true; rows for
+ which it evaluates to false or null are eliminated.
+ </para>
+
+ <para>
+ The condition may contain window functions, whether or not the same
+ window functions also appear in the <command>SELECT</command> list.
+ These window functions may use an inline <literal>OVER</literal>
+ clause or refer to a window defined in the
+ <link linkend="sql-window"><literal>WINDOW</literal></link> clause; a
+ <literal>WINDOW</literal> clause is not required. Because
+ <literal>QUALIFY</literal> is evaluated after the
+ <command>SELECT</command> list, the condition may also reference
+ output column names (column aliases defined in the
+ <command>SELECT</command> list), unlike <literal>WHERE</literal> and
+ <literal>HAVING</literal>. In case of ambiguity, a name in
+ <literal>QUALIFY</literal> is interpreted as an input-column name
+ rather than an output column name.
+ </para>
+
+ <para>
+ <literal>QUALIFY</literal> does not require window functions to be
+ present; it is a general filter applied to the computed output rows.
+ A condition that does not involve a window function and refers only to
+ input columns produces the same result as if it had been written in
+ <literal>WHERE</literal>, though writing such conditions in
+ <literal>WHERE</literal> is preferred. Aggregate functions are
+ permitted in the condition under the same rules that apply to the
+ <command>SELECT</command> list, since aggregation has already occurred
+ by the time <literal>QUALIFY</literal> is evaluated.
+ </para>
+
+ <para>
+ The following query returns, for each department, only the
+ highest-paid employees, filtering on the result of a window function
+ without a sub-query:
+<programlisting>
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS pos
+FROM empsalary
+QUALIFY pos = 1;
+</programlisting>
+ Here the output column name <literal>pos</literal> defined in the
+ <command>SELECT</command> list is referenced in
+ <literal>QUALIFY</literal>. The window function could equally be
+ spelled out in the <literal>QUALIFY</literal> condition itself, in
+ which case it need not appear in the <command>SELECT</command> list at
+ all.
+ </para>
+ </refsect2>
+
<refsect2 id="sql-distinct" xreflabel="DISTINCT Clause">
<title><literal>DISTINCT</literal> Clause</title>
@@ -2045,6 +2133,17 @@ FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
missing features.
</para>
+ <refsect2>
+ <title>The <literal>QUALIFY</literal> Clause</title>
+
+ <para>
+ The <literal>QUALIFY</literal> clause conforms to the SQL standard
+ (feature O001, <quote>QUALIFY clause</quote>). Note that
+ <literal>QUALIFY</literal> is a reserved word; existing applications
+ that use it as an identifier must quote it or choose another name.
+ </para>
+ </refsect2>
+
<refsect2>
<title>Omitted <literal>FROM</literal> Clauses</title>
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 2a2e00b372e..36cae30c0b3 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -4488,6 +4488,8 @@ raw_expression_tree_walker_impl(Node *node,
return true;
if (WALK(stmt->rarg))
return true;
+ if (WALK(stmt->qualifyClause))
+ return true;
}
break;
case T_PLAssignStmt:
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 2932d17a107..f17252f891e 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -52,6 +52,7 @@
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
+#include "rewrite/rewriteManip.h"
#include "utils/backend_status.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
@@ -70,6 +71,31 @@ typedef struct SelectStmtPassthrough
List *indirection; /* indirection yet to be applied to target */
} SelectStmtPassthrough;
+/* State for the QUALIFY select-list alias resolution hook */
+typedef struct QualifyHookState
+{
+ List *targetList; /* target list to match aliases against */
+ PostParseColumnRefHook prev_hook; /* previously installed hook, if any */
+ void *prev_hook_state; /* its state */
+} QualifyHookState;
+
+/* Working state for qualifyExtractMutator */
+typedef struct QualifyExtractContext
+{
+ List **innerTargetList; /* inner query's target list (appended to) */
+ int subquery_varno; /* varno of the subquery RTE in the outer
+ * query */
+ int next_resno; /* next resno to assign to appended entries */
+} QualifyExtractContext;
+
+/* Working state for qualifyFixupVarattno */
+typedef struct QualifyVarmapContext
+{
+ int subquery_varno; /* varno whose Vars are to be remapped */
+ AttrNumber *attmap; /* map from old resno to new resno */
+} QualifyVarmapContext;
+
+
/* Hook for plugins to get control at end of parse analysis */
post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
@@ -108,6 +134,10 @@ static Query *transformCallStmt(ParseState *pstate,
CallStmt *stmt);
static void transformLockingClause(ParseState *pstate, Query *qry,
LockingClause *lc, bool pushedDown);
+static Node *qualifyPostColumnRefHook(ParseState *pstate, ColumnRef *cref,
+ Node *var);
+static Query *rewriteQualifyQuery(ParseState *pstate, Query *innerQuery,
+ Node *qualifyExpr);
#ifdef DEBUG_NODE_TESTS_ENABLED
static bool test_raw_expression_coverage(Node *node, void *context);
#endif
@@ -1724,6 +1754,427 @@ count_rowexpr_columns(ParseState *pstate, Node *expr)
return -1;
}
+/*
+ * qualifyPostColumnRefHook
+ * Resolve a QUALIFY column references
+ *
+ * QUALIFY column references can reference table columns and target alias. A
+ * real column of the FROM tables take precedence over a select-list alias of
+ * the same name.
+ */
+static Node *
+qualifyPostColumnRefHook(ParseState *pstate, ColumnRef *cref, Node *var)
+{
+ QualifyHookState *qstate = (QualifyHookState *) pstate->p_ref_hook_state;
+ char *name;
+ TargetEntry *matched = NULL;
+ ListCell *lc;
+
+ /* A real column of the FROM tables takes precedence over an alias. */
+ if (var != NULL)
+ return NULL;
+
+ /* Only unqualified (single-field) names can match a select-list alias. */
+ if (list_length(cref->fields) != 1 || !IsA(linitial(cref->fields), String))
+ return NULL;
+
+ name = strVal(linitial(cref->fields));
+
+ foreach(lc, qstate->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resjunk || tle->resname == NULL || strcmp(tle->resname, name) != 0)
+ continue;
+
+ if (matched != NULL && !equal(matched->expr, tle->expr))
+ ereport(ERROR,
+ (errcode(ERRCODE_AMBIGUOUS_COLUMN),
+ errmsg("column reference \"%s\" is ambiguous", name),
+ parser_errposition(pstate, cref->location)));
+ matched = tle;
+ }
+
+ if (matched == NULL)
+ return NULL;
+
+ /*
+ * XXX: an alias whose expression is non-deterministic would be evaluated
+ * once for the select-list column and again in the outer filter built
+ * from the QUALIFY condition, possibly producing different values. Until
+ * such references are resolved by the identity of the select-list entry
+ * (projecting it once and referencing it by a single Var), reject
+ * volatile alias expressions.
+ */
+ if (contain_volatile_functions((Node *) matched->expr))
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("QUALIFY cannot reference output column \"%s\" whose expression is non-deterministic",
+ name),
+ parser_errposition(pstate, cref->location)));
+
+ return copyObject(matched->expr);
+}
+
+/*
+ * qualifyExtractMutator
+ * Rewrite a QUALIFY condition so it can serve as the WHERE clause of the
+ * outer query built by rewriteQualifyQuery.
+ *
+ * Every window function, aggregate, and Var of the inner query is computed by
+ * the inner query and referenced from the outer query by a plain Var: we find
+ * an existing target entry with an equal expression, or append a new resjunk
+ * one, and replace the node with an outer Var. Comparisons and other
+ * operators are left in place at the outer level. This reproduces the shape
+ * of a hand-written subquery, so the planner's existing optimizations for
+ * window functions in subqueries (run conditions and qual pushdown) apply
+ * unchanged.
+ */
+static Node *
+qualifyExtractMutator(Node *node, QualifyExtractContext *ctx)
+{
+ if (node == NULL)
+ return NULL;
+
+ if (IsA(node, WindowFunc) || IsA(node, Aggref)
+ || (IsA(node, Var) && ((Var *) node)->varlevelsup == 0))
+ {
+ TargetEntry *tle = NULL;
+
+ /* Reuse a matching target entry so a value isn't projected twice. */
+ foreach_ptr(TargetEntry, cur, *ctx->innerTargetList)
+ {
+ if (equal(cur->expr, node))
+ {
+ tle = cur;
+ break;
+ }
+ }
+
+ /*
+ * Did not find the target entry on target list so add it on inner
+ * query target list so it can be referenced on the outer query.
+ */
+ if (tle == NULL)
+ {
+ tle = makeTargetEntry((Expr *) copyObject(node),
+ ctx->next_resno++,
+ NULL,
+ false);
+ *ctx->innerTargetList = lappend(*ctx->innerTargetList, tle);
+ }
+
+ /*
+ * The entry is referenced from the outer query, so it must be a real
+ * (non-resjunk) output column of the subquery. A reused entry might
+ * be a resjunk grouping column or a junk ORDER BY/DISTINCT target, so
+ * clear the flag here.
+ */
+ tle->resjunk = false;
+
+ return (Node *) makeVarFromTargetEntry(ctx->subquery_varno, tle);
+ }
+
+ return expression_tree_mutator(node, qualifyExtractMutator, ctx);
+}
+
+/*
+ * qualifyFixupVarattno
+ * Remap the attribute numbers of Vars referencing the QUALIFY subquery,
+ * after the subquery's target list has been renumbered.
+ */
+static bool
+qualifyFixupVarattno(Node *node, QualifyVarmapContext *ctx)
+{
+ if (node == NULL)
+ return false;
+
+ if (IsA(node, Var))
+ {
+ Var *var = (Var *) node;
+
+ if (var->varlevelsup == 0 && var->varno == ctx->subquery_varno)
+ {
+ var->varattno = ctx->attmap[var->varattno];
+ var->varattnosyn = var->varattno;
+ }
+ return false;
+ }
+
+ return expression_tree_walker(node, qualifyFixupVarattno, ctx);
+}
+
+/*
+ * rewriteQualifyQuery
+ * Implement the QUALIFY clause by rewriting the inner query in an outer
+ * query whose WHERE clause is the QUALIFY condition.
+ *
+ * 'innerQuery' is the fully-analyzed query for the table expression and select
+ * list, with the resolved QUALIFY condition appended to its target list as a
+ * resjunk entry. We remove that entry, decompose the condition into the outer
+ * WHERE clause (extracting window functions, aggregates, and inner Vars into
+ * the inner target list), and process the deferred ORDER BY, DISTINCT, and
+ * LIMIT clauses against the outer query.
+ */
+static Query *
+rewriteQualifyQuery(ParseState *pstate, Query *innerQuery, Node *qualifyExpr)
+{
+ Query *outerQuery = makeNode(Query);
+ List *outerTargetList = NIL;
+ List *origTargetList = NIL;
+ List *nonjunk = NIL;
+ List *junk = NIL;
+ Bitmapset *liftrefs = NULL;
+ ParseState *opstate;
+ ParseNamespaceItem *nsitem;
+ QualifyExtractContext ctx;
+ Node *outerQual;
+ List *outerSortClause;
+ List *outerDistinctClause;
+ bool outerHasDistinctOn;
+ Node *outerLimitOffset;
+ Node *outerLimitCount;
+ LimitOption outerLimitOption;
+ ListCell *lc;
+ int resno;
+ int ntargets;
+ AttrNumber *attmap;
+ QualifyVarmapContext mapctx;
+ AttrNumber newresno;
+
+ /*
+ * ORDER BY, DISTINCT, and LIMIT were transformed against the inner
+ * query's scope but are logically evaluated after QUALIFY, so they move
+ * to the outer query. Detach them from the inner query; the sort and
+ * distinct clauses are re-attached below after the columns they reference
+ * are exposed as subquery outputs.
+ */
+ outerSortClause = innerQuery->sortClause;
+ outerDistinctClause = innerQuery->distinctClause;
+ outerHasDistinctOn = innerQuery->hasDistinctOn;
+ outerLimitOffset = innerQuery->limitOffset;
+ outerLimitCount = innerQuery->limitCount;
+ outerLimitOption = innerQuery->limitOption;
+ innerQuery->sortClause = NIL;
+ innerQuery->distinctClause = NIL;
+ innerQuery->hasDistinctOn = false;
+ innerQuery->limitOffset = NULL;
+ innerQuery->limitCount = NULL;
+ innerQuery->limitOption = LIMIT_OPTION_COUNT;
+
+ /* Collect the sort/group refs that the lifted ORDER BY / DISTINCT use. */
+ foreach(lc, outerSortClause)
+ liftrefs = bms_add_member(liftrefs,
+ ((SortGroupClause *) lfirst(lc))->tleSortGroupRef);
+ foreach(lc, outerDistinctClause)
+ liftrefs = bms_add_member(liftrefs,
+ ((SortGroupClause *) lfirst(lc))->tleSortGroupRef);
+
+ /*
+ * Remove the temporary resjunk QUALIFY entry from the inner target list
+ * required by parseCheckAggregates.
+ */
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->expr == (Expr *) qualifyExpr)
+ {
+ Assert(tle->resjunk);
+ innerQuery->targetList = foreach_delete_current(innerQuery->targetList, lc);
+ break;
+ }
+ }
+
+ /*
+ * Capture the original select-list output columns now, before extraction
+ * and lifting may append further (non-resjunk) columns or un-junk
+ * grouping/sort columns; these are what the outer query projects.
+ */
+ foreach_ptr(TargetEntry, tle, innerQuery->targetList)
+ {
+ if (!tle->resjunk)
+ origTargetList = lappend(origTargetList, tle);
+ }
+
+ /*
+ * Extract the QUALIFY condition into the outer WHERE clause, projecting
+ * the inner-query expressions it needs through the subquery. The subquery
+ * will be range-table entry 1 of the outer query.
+ */
+ ctx.innerTargetList = &innerQuery->targetList;
+ ctx.subquery_varno = 1;
+ ctx.next_resno = list_length(innerQuery->targetList) + 1;
+ outerQual = qualifyExtractMutator(qualifyExpr, &ctx);
+
+ /*
+ * Expose as non-resjunk subquery outputs, the inner columns that the
+ * lifted ORDER BY / DISTINCT clauses reference, so the outer query can
+ * refer to them. Grouping columns not referenced by ORDER BY/DISTINCT
+ * stay resjunk.
+ */
+ foreach_ptr(TargetEntry, tle, innerQuery->targetList)
+ {
+ if (tle->ressortgroupref != 0 && bms_is_member(tle->ressortgroupref, liftrefs))
+ tle->resjunk = false;
+ }
+
+ /*
+ * A subquery range table entry requires its non-resjunk columns to come
+ * first with contiguous resnos, and every output column must have a name.
+ * Reorder the inner target list accordingly, name any anonymous output
+ * columns, and remap the resnos referenced by the outer WHERE clause.
+ */
+ ntargets = list_length(innerQuery->targetList);
+ attmap = (AttrNumber *) palloc0((ntargets + 1) * sizeof(AttrNumber));
+
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resjunk)
+ junk = lappend(junk, tle);
+ else
+ nonjunk = lappend(nonjunk, tle);
+ }
+ innerQuery->targetList = list_concat(nonjunk, junk);
+
+ newresno = 1;
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ attmap[tle->resno] = newresno;
+ tle->resno = newresno;
+
+ /*
+ * Output columns created by extraction are anonymous. Give a Var the
+ * name of its source column, so the lifted ORDER BY/DISTINCT and the
+ * outer WHERE can reference an input column (e.g. "QUALIFY x > 0
+ * ORDER BY x"); fall back to a generated name for non-Var
+ * expressions.
+ */
+ if (!tle->resjunk && tle->resname == NULL)
+ {
+ if (IsA(tle->expr, Var) && ((Var *) tle->expr)->varattno > 0)
+ {
+ Var *var = (Var *) tle->expr;
+
+ tle->resname = get_rte_attribute_name(rt_fetch(var->varno,
+ innerQuery->rtable),
+ var->varattno);
+ }
+ if (tle->resname == NULL)
+ tle->resname = psprintf("qualify%d", newresno);
+ }
+ newresno++;
+ }
+
+ /* Now fix the QUALIFY Var references */
+ mapctx.subquery_varno = ctx.subquery_varno;
+ mapctx.attmap = attmap;
+ qualifyFixupVarattno(outerQual, &mapctx);
+
+ /*
+ * The inner query is now one level deeper than it was, so bump the level
+ * of any outer references it contains. The outer WHERE clause (and the
+ * lifted clauses) stay at the current level.
+ */
+ IncrementVarSublevelsUp((Node *) innerQuery, 1, 1);
+
+ /* Build the outer query's parse state, sharing the original parent. */
+ opstate = make_parsestate(pstate->parentParseState);
+ opstate->p_sourcetext = pstate->p_sourcetext;
+ opstate->p_pre_columnref_hook = pstate->p_pre_columnref_hook;
+ opstate->p_post_columnref_hook = pstate->p_post_columnref_hook;
+ opstate->p_paramref_hook = pstate->p_paramref_hook;
+ opstate->p_coerce_param_hook = pstate->p_coerce_param_hook;
+ opstate->p_ref_hook_state = pstate->p_ref_hook_state;
+
+ outerQuery->commandType = CMD_SELECT;
+
+ nsitem = addRangeTableEntryForSubquery(opstate, innerQuery,
+ makeAlias("pg_qualify", NIL),
+ false, true);
+ addNSItemToQuery(opstate, nsitem, true, true, true);
+
+ /* Outer target list: project the original select-list output columns. */
+ resno = 1;
+ foreach(lc, origTargetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+ Var *var = makeVarFromTargetEntry(ctx.subquery_varno, tle);
+
+ outerTargetList = lappend(outerTargetList,
+ makeTargetEntry((Expr *) var,
+ resno++,
+ tle->resname ? pstrdup(tle->resname) : NULL,
+ false));
+ }
+
+ /*
+ * Re-attach the lifted ORDER BY / DISTINCT clauses. For each inner
+ * column they reference, give the outer target that projects it the same
+ * sort/ group ref so the moved SortGroupClauses line up; a referenced
+ * column not in the projection gets a resjunk outer target.
+ */
+ foreach_ptr(TargetEntry, innerTle, innerQuery->targetList)
+ {
+ TargetEntry *out = NULL;
+
+ if (innerTle->ressortgroupref == 0 || !bms_is_member(innerTle->ressortgroupref, liftrefs))
+ continue;
+
+ foreach_ptr(TargetEntry, outerTle, outerTargetList)
+ {
+
+ if (IsA(outerTle->expr, Var) && ((Var *) outerTle->expr)->varattno == innerTle->resno)
+ {
+ out = outerTle;
+ break;
+ }
+ }
+
+ if (out == NULL)
+ {
+ Var *var = makeVarFromTargetEntry(ctx.subquery_varno, innerTle);
+
+ out = makeTargetEntry((Expr *) var,
+ resno++,
+ innerTle->resname ? pstrdup(innerTle->resname) : NULL,
+ true);
+ outerTargetList = lappend(outerTargetList, out);
+ }
+ out->ressortgroupref = innerTle->ressortgroupref;
+ }
+
+ outerQuery->targetList = outerTargetList;
+ outerQuery->rtable = opstate->p_rtable;
+ outerQuery->rteperminfos = opstate->p_rteperminfos;
+ outerQuery->jointree = makeFromExpr(opstate->p_joinlist, outerQual);
+
+ outerQuery->sortClause = outerSortClause;
+ outerQuery->distinctClause = outerDistinctClause;
+ outerQuery->hasDistinctOn = outerHasDistinctOn;
+ outerQuery->limitOffset = outerLimitOffset;
+ outerQuery->limitCount = outerLimitCount;
+ outerQuery->limitOption = outerLimitOption;
+
+ /*
+ * The outer query has no aggregates or window functions (those were
+ * extracted into the subquery), so only sub-links need to be reported.
+ */
+ outerQuery->hasSubLinks = checkExprHasSubLink(outerQual) ||
+ checkExprHasSubLink(outerLimitOffset) ||
+ checkExprHasSubLink(outerLimitCount);
+
+ assign_query_collations(opstate, outerQuery);
+
+ free_parsestate(opstate);
+
+ return outerQuery;
+}
+
/*
* transformSelectStmt -
@@ -1746,6 +2197,8 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
Query *qry = makeNode(Query);
Node *qual;
ListCell *l;
+ bool hasQualify = (stmt->qualifyClause != NULL);
+ Node *qualifyExpr = NULL;
qry->commandType = CMD_SELECT;
@@ -1802,6 +2255,13 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
* transformGroupClause and transformDistinctClause need the results. Note
* that these functions can also change the targetList, so it's passed to
* them by reference.
+ *
+ * When a QUALIFY clause is present, ORDER BY/DISTINCT/LIMIT are logically
+ * evaluated after QUALIFY and so belong to the outer query that
+ * rewriteQualifyQuery() builds. We still transform them here, against
+ * the inner query's scope, so that they can reference input columns and
+ * select-list aliases as in any other query; rewriteQualifyQuery() then
+ * lifts the resulting clauses out to the outer query.
*/
qry->sortClause = transformSortClause(pstate,
stmt->sortClause,
@@ -1853,6 +2313,42 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
stmt->limitOption);
qry->limitOption = stmt->limitOption;
+ /*
+ * Transform the QUALIFY condition, if any. This must happen before
+ * transformWindowDefinitions() so that window functions appearing only in
+ * QUALIFY get their inline window specifications registered and turned
+ * into WindowClauses. QUALIFY may reference select-list aliases, so we
+ * install a post-columnref hook that resolves a bare name to a
+ * select-list alias.
+ *
+ * The resolved condition is appended to the target list as a resjunk
+ * entry so that parseCheckAggregates() validates it like a select-list
+ * item; it is removed and decomposed into the outer query's WHERE clause
+ * by rewriteQualifyQuery() below.
+ */
+ if (hasQualify)
+ {
+ QualifyHookState qstate;
+
+ qstate.targetList = qry->targetList;
+ qstate.prev_hook = pstate->p_post_columnref_hook;
+ qstate.prev_hook_state = pstate->p_ref_hook_state;
+ pstate->p_post_columnref_hook = qualifyPostColumnRefHook;
+ pstate->p_ref_hook_state = &qstate;
+
+ qualifyExpr = transformWhereClause(pstate, stmt->qualifyClause,
+ EXPR_KIND_QUALIFY, "QUALIFY");
+
+ pstate->p_post_columnref_hook = qstate.prev_hook;
+ pstate->p_ref_hook_state = qstate.prev_hook_state;
+
+ qry->targetList = lappend(qry->targetList,
+ makeTargetEntry((Expr *) qualifyExpr,
+ list_length(qry->targetList) + 1,
+ NULL,
+ true));
+ }
+
/* transform window clauses after we have seen all window functions */
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
@@ -1883,6 +2379,14 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
parseCheckAggregates(pstate, qry);
+ /*
+ * If a QUALIFY clause was present, wrap the query just built (the inner
+ * query) in an outer query whose WHERE clause is the QUALIFY condition,
+ * and process the deferred ORDER BY/DISTINCT/LIMIT clauses against it.
+ */
+ if (hasQualify)
+ return rewriteQualifyQuery(pstate, qry, qualifyExpr);
+
return qry;
}
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index ff4e1388c55..942beb1ecb6 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -532,7 +532,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <node> TableElement TypedTableElement ConstraintElem DomainConstraintElem TableFuncElement
%type <node> columnDef columnOptions optionalPeriodName
%type <defelt> def_elem reloption_elem old_aggr_elem operator_def_elem
-%type <node> def_arg columnElem where_clause where_or_current_clause
+%type <node> def_arg columnElem where_clause qualify_clause where_or_current_clause
a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound
columnref having_clause func_table xmltable array_expr
OptWhereClause operator_def_arg
@@ -806,7 +806,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PROPERTIES PROPERTY PUBLICATION
- QUOTE QUOTES
+ QUALIFY QUOTE QUOTES
RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING
REFRESH REINDEX RELATIONSHIP RELATIVE_P RELEASE RENAME REPACK REPEATABLE REPLACE REPLICA
@@ -13741,7 +13741,7 @@ select_clause:
simple_select:
SELECT opt_all_clause opt_target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13754,11 +13754,12 @@ simple_select:
n->groupByAll = ($7)->all;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| SELECT distinct_clause target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13772,6 +13773,7 @@ simple_select:
n->groupByAll = ($7)->all;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| values_clause { $$ = $1; }
@@ -14959,6 +14961,11 @@ where_clause:
| /*EMPTY*/ { $$ = NULL; }
;
+qualify_clause:
+ QUALIFY a_expr { $$ = $2; }
+ | /*EMPTY*/ { $$ = NULL; }
+ ;
+
/* variant for UPDATE and DELETE */
where_or_current_clause:
WHERE a_expr { $$ = $2; }
@@ -19346,6 +19353,7 @@ reserved_keyword:
| ORDER
| PLACING
| PRIMARY
+ | QUALIFY
| REFERENCES
| RETURNING
| SELECT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index acb933392de..8153b074e55 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -407,6 +407,9 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ /* okay */
+ break;
case EXPR_KIND_POLICY:
if (isAgg)
err = _("aggregate functions are not allowed in policy expressions");
@@ -964,6 +967,7 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
err = _("window functions are not allowed in window definitions");
break;
case EXPR_KIND_SELECT_TARGET:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 9adc9d4c0f6..7633e32f915 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -579,6 +579,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_GENERATED_COLUMN:
case EXPR_KIND_CYCLE_MARK:
case EXPR_KIND_PROPGRAPH_PROPERTY:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
@@ -1820,6 +1821,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FROM_SUBSELECT:
case EXPR_KIND_FROM_FUNCTION:
case EXPR_KIND_WHERE:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
case EXPR_KIND_FILTER:
@@ -3180,6 +3182,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "function in FROM";
case EXPR_KIND_WHERE:
return "WHERE";
+ case EXPR_KIND_QUALIFY:
+ return "QUALIFY";
case EXPR_KIND_POLICY:
return "POLICY";
case EXPR_KIND_HAVING:
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index fb306c05112..0bb8371cdd9 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -2690,6 +2690,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
err = _("set-returning functions are not allowed in policy expressions");
break;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 4133c404a6b..9da8f9a27b2 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -2300,6 +2300,7 @@ typedef struct SelectStmt
bool groupByAll; /* Is this GROUP BY ALL? */
Node *havingClause; /* HAVING conditional-expression */
List *windowClause; /* WINDOW window_name AS (...), ... */
+ Node *qualifyClause; /* QUALIFY conditional-expression */
/*
* In a "leaf" node representing a VALUES list, the above fields are all
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 51ead54f015..a83545931c1 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -370,6 +370,7 @@ PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("properties", PROPERTIES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("property", PROPERTY, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("qualify", QUALIFY, RESERVED_KEYWORD, AS_LABEL)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("quotes", QUOTES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f7f4ba6c2a8..2443a1192d4 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -45,6 +45,7 @@ typedef enum ParseExprKind
EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
EXPR_KIND_WHERE, /* WHERE */
EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_QUALIFY, /* QUALIFY */
EXPR_KIND_FILTER, /* FILTER */
EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
diff --git a/src/test/regress/expected/qualify.out b/src/test/regress/expected/qualify.out
new file mode 100644
index 00000000000..ae55a556449
--- /dev/null
+++ b/src/test/regress/expected/qualify.out
@@ -0,0 +1,1122 @@
+--
+-- QUALIFY clause tests
+--
+CREATE TEMPORARY TABLE empsalary (
+ depname varchar,
+ empno bigint,
+ salary int,
+ enroll_date date
+);
+INSERT INTO empsalary VALUES
+('develop', 10, 5200, '2007-08-01'),
+('sales', 1, 5000, '2006-10-01'),
+('personnel', 5, 3500, '2007-12-10'),
+('sales', 4, 4800, '2007-08-08'),
+('personnel', 2, 3900, '2006-12-23'),
+('develop', 7, 4200, '2008-01-01'),
+('develop', 9, 4500, '2008-01-01'),
+('sales', 3, 4800, '2007-08-01'),
+('develop', 8, 6000, '2006-10-01'),
+('develop', 11, 5200, '2007-08-15');
+--
+-- Basic QUALIFY functionality
+--
+-- Simple QUALIFY with inline window function
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rank
+-----------+-------+--------+------
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+-- QUALIFY with named window
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rank
+-----------+-------+--------+------
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+--
+-- Alias resolution tests
+--
+-- Reference alias defined in SELECT
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rnk
+-----------+-------+--------+-----
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+-- Reference alias with row_number
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 < 3)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- Multiple aliases
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: ((pg_qualify.rn = 1) OR (pg_qualify.rnk <= 2))
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2
+ORDER BY depname, salary DESC;
+ depname | empno | salary | rn | rnk
+-----------+-------+--------+----+-----
+ develop | 8 | 6000 | 1 | 1
+ develop | 10 | 5200 | 2 | 2
+ develop | 11 | 5200 | 3 | 2
+ personnel | 2 | 3900 | 1 | 1
+ personnel | 5 | 3500 | 2 | 2
+ sales | 1 | 5000 | 1 | 1
+ sales | 4 | 4800 | 2 | 2
+ sales | 3 | 4800 | 3 | 2
+(8 rows)
+
+--
+-- Run condition optimization tests
+--
+-- row_number with < operator (should use run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 < 3)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- row_number with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- rank with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- dense_rank with = operator (should convert to <= for run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.dr = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (dense_rank() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+ empno | salary | dr
+-------+--------+----
+ 8 | 6000 | 1
+(1 row)
+
+-- count(*) with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+ QUERY PLAN
+---------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary)
+ Run Condition: (count(*) OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+ empno | salary | c
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 3
+ 11 | 5200 | 3
+(3 rows)
+
+--
+-- WHERE pushdown tests
+-- Quals on PARTITION BY columns without window functions can be pushed to WHERE
+--
+-- depname is in PARTITION BY, should be pushed to WHERE (SeqScan filter)
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop';
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'develop'::text)
+(7 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop'
+ORDER BY salary DESC;
+ depname | empno | salary | rnk
+---------+-------+--------+-----
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+(3 rows)
+
+-- Mixed: depname pushed to WHERE, rank condition stays as run condition
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rnk = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'sales'::text)
+(9 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+ depname | empno | salary | rnk
+---------+-------+--------+-----
+ sales | 1 | 5000 | 1
+(1 row)
+
+--
+-- QUALIFY without window function in SELECT list
+-- The window function appears only in QUALIFY
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify4 = 1)
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+ depname | empno | salary
+-----------+-------+--------
+ develop | 8 | 6000
+ personnel | 2 | 3900
+ sales | 1 | 5000
+(3 rows)
+
+-- With PARTITION BY column filter pushed down
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify4 = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'develop'::text)
+(9 rows)
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+ depname | empno | salary
+---------+-------+--------
+ develop | 8 | 6000
+(1 row)
+
+--
+-- Multiple window functions with different windows
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: ((pg_qualify.rn_asc = 1) OR (pg_qualify.rn_desc = 1))
+ -> WindowAgg
+ Window: w2 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Incremental Sort
+ Sort Key: empsalary.depname, empsalary.salary
+ Presorted Key: empsalary.depname
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(12 rows)
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1
+ORDER BY depname, empno;
+ depname | empno | salary | rn_asc | rn_desc
+-----------+-------+--------+--------+---------
+ develop | 7 | 4200 | 1 | 5
+ develop | 8 | 6000 | 5 | 1
+ personnel | 2 | 3900 | 2 | 1
+ personnel | 5 | 3500 | 1 | 2
+ sales | 1 | 5000 | 3 | 1
+ sales | 4 | 4800 | 1 | 2
+(6 rows)
+
+--
+-- QUALIFY with aggregate and window functions
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ -> WindowAgg
+ Window: w1 AS (ORDER BY (sum(empsalary.salary)) ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: (sum(empsalary.salary)) DESC
+ -> HashAggregate
+ Group Key: empsalary.depname
+ -> Seq Scan on empsalary
+(9 rows)
+
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+ depname | total | rnk
+---------+-------+-----
+ develop | 25100 | 1
+ sales | 14600 | 2
+(2 rows)
+
+--
+-- QUALIFY in a grouped query without window functions.
+-- The condition is validated like a SELECT-list item, so aggregates and
+-- grouping columns are allowed (and behave as HAVING would).
+--
+-- Aggregate used directly in QUALIFY filters groups like HAVING
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY count(*) > 2
+ORDER BY depname;
+ depname | c
+---------+---
+ develop | 5
+ sales | 3
+(2 rows)
+
+-- A grouping column may be referenced directly in QUALIFY
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY depname <> 'sales'
+ORDER BY depname;
+ depname | c
+-----------+---
+ develop | 5
+ personnel | 2
+(2 rows)
+
+--
+-- Comparison with equivalent subquery (results should match)
+--
+-- Subquery version
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- QUALIFY version (should produce same results)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+--
+-- QUALIFY with different comparison operators
+--
+-- Greater than (no run condition optimization for increasing functions)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn > 7)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7
+ORDER BY empno;
+ empno | rn
+-------+----
+ 9 | 8
+ 10 | 9
+ 11 | 10
+(3 rows)
+
+-- Equality
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn = 5)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+ empno | rn
+-------+----
+ 5 | 5
+(1 row)
+
+-- BETWEEN (should keep as filter)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn >= 3)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5
+ORDER BY empno;
+ empno | rn
+-------+----
+ 3 | 3
+ 4 | 4
+ 5 | 5
+(3 rows)
+
+-- IN list
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5);
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn = ANY ('{1,3,5}'::bigint[]))
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5)
+ORDER BY empno;
+ empno | rn
+-------+----
+ 1 | 1
+ 3 | 3
+ 5 | 5
+(3 rows)
+
+--
+-- QUALIFY with expressions
+--
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+ empno | salary | rn
+-------+--------+----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 3
+ 1 | 5000 | 4
+ 4 | 4800 | 5
+(5 rows)
+
+--
+-- Error cases
+--
+-- Aggregate in QUALIFY without GROUP BY: just as in the SELECT list, the
+-- non-aggregated output columns make this an error (must appear in GROUP BY).
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY sum(salary) > 5000;
+ERROR: column "empsalary.depname" must appear in the GROUP BY clause or be used in an aggregate function
+LINE 1: SELECT depname, empno, salary
+ ^
+-- QUALIFY in a grouped query referencing an ungrouped column (should error,
+-- just as such a reference would in the SELECT list)
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY salary > 100;
+ERROR: column "empsalary.salary" must appear in the GROUP BY clause or be used in an aggregate function
+LINE 4: QUALIFY salary > 100;
+ ^
+-- QUALIFY with set-returning function (should error)
+SELECT empno, salary
+FROM empsalary
+QUALIFY generate_series(1, 3) > 1;
+ERROR: set-returning functions are not allowed in QUALIFY
+LINE 3: QUALIFY generate_series(1, 3) > 1;
+ ^
+--
+-- QUALIFY in different query structures
+--
+-- With DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------
+ Unique
+ -> Incremental Sort
+ Sort Key: pg_qualify.depname, pg_qualify.top_emp
+ Presorted Key: pg_qualify.depname
+ -> Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify3 = 1)
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(12 rows)
+
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+ depname | top_emp
+-----------+---------
+ develop | 8
+ personnel | 2
+ sales | 1
+(3 rows)
+
+-- With ORDER BY
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | rnk
+-------+--------+-----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- With LIMIT (QUALIFY is evaluated before LIMIT)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+LIMIT 3;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Limit
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+ORDER BY salary DESC
+LIMIT 3;
+ empno | salary | rn
+-------+--------+----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 3
+(3 rows)
+
+--
+-- Verify evaluation order: QUALIFY happens after window functions, before DISTINCT
+--
+-- This should first compute row_number, then filter, then apply DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ HashAggregate
+ Group Key: empsalary.salary, row_number() OVER w1
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+ salary | rn
+--------+----
+ 5200 | 2
+ 5200 | 3
+ 6000 | 1
+(3 rows)
+
+-- QUALIFY with FILTERS over window function
+EXPLAIN(COSTS OFF) SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rank = 1)
+ -> WindowAgg
+ Window: w2 AS (ORDER BY empsalary.depname ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w2 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.depname)
+ -> Sort
+ Sort Key: empsalary.depname DESC
+ -> HashAggregate
+ Group Key: empsalary.depname
+ -> Seq Scan on empsalary
+(14 rows)
+
+SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+ sum | rank | filtered_sum | depname
+-------+------+--------------+---------
+ 25100 | 1 | 22600 | develop
+(1 row)
+
+--
+-- Aggregate functions directly in QUALIFY
+-- (allowed in a grouped query, the same as in the SELECT list / HAVING)
+--
+-- Aggregate condition over the group
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000;
+ QUERY PLAN
+-------------------------------------------------
+ Subquery Scan on pg_qualify
+ -> HashAggregate
+ Group Key: empsalary.depname
+ Filter: (sum(empsalary.salary) > 15000)
+ -> Seq Scan on empsalary
+(5 rows)
+
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000
+ORDER BY depname;
+ depname | total
+---------+-------
+ develop | 25100
+(1 row)
+
+-- Aggregate and window function combined in QUALIFY
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY rank() OVER (ORDER BY sum(salary) DESC) = 1
+ORDER BY depname;
+ depname | total
+---------+-------
+ develop | 25100
+(1 row)
+
+-- Whole-table aggregate (single group)
+SELECT sum(salary) AS s
+FROM empsalary
+QUALIFY sum(salary) > 1000;
+ s
+-------
+ 47100
+(1 row)
+
+--
+-- Name resolution tests
+--
+-- An input column takes precedence over a same-named select-list alias
+-- "salary" in QUALIFY is the input column (> 4000 keeps most rows), not the
+-- alias (which is 0 and would keep none)
+SELECT empno, (empno * 0) AS salary
+FROM empsalary
+QUALIFY salary > 4000
+ORDER BY empno;
+ empno | salary
+-------+--------
+ 1 | 0
+ 3 | 0
+ 4 | 0
+ 7 | 0
+ 8 | 0
+ 9 | 0
+ 10 | 0
+ 11 | 0
+(8 rows)
+
+-- QUALIFY referecing columns that not on output result
+-- Same column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY salary;
+ depname
+-----------
+ personnel
+ personnel
+ develop
+ develop
+ sales
+ sales
+ sales
+ develop
+ develop
+ develop
+(10 rows)
+
+-- Different column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY enroll_date;
+ depname
+-----------
+ sales
+ develop
+ personnel
+ sales
+ develop
+ sales
+ develop
+ personnel
+ develop
+ develop
+(10 rows)
+
+--
+-- Name resolution error cases
+--
+-- A non-deterministic alias expression cannot be referenced from QUALIFY
+SELECT empno, (random() < 2)::int AS r
+FROM empsalary
+QUALIFY r = 1;
+ERROR: QUALIFY cannot reference output column "r" whose expression is non-deterministic
+LINE 3: QUALIFY r = 1;
+ ^
+-- An ambiguous alias reference is rejected
+SELECT empno AS x, salary AS x,
+ row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY x > 0;
+ERROR: column reference "x" is ambiguous
+LINE 4: QUALIFY x > 0;
+ ^
+-- A name that is neither an input column nor a select-list alias
+SELECT empno
+FROM empsalary
+QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+ERROR: column "nosuchcol" does not exist
+LINE 3: QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+ ^
+--
+-- QUALIFY without any window function: a general post-SELECT filter
+--
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000;
+ QUERY PLAN
+----------------------------------
+ Seq Scan on empsalary
+ Filter: ((salary * 2) > 10000)
+(2 rows)
+
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000
+ORDER BY empno;
+ empno | salary | new_salary
+-------+--------+------------
+ 8 | 6000 | 12000
+ 10 | 5200 | 10400
+ 11 | 5200 | 10400
+(3 rows)
+
+--
+-- QUALIFY in other query structures
+--
+-- In the arms of a set operation
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary) = 1
+UNION ALL
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary DESC) = 1
+ORDER BY empno;
+ empno
+-------
+ 5
+ 8
+(2 rows)
+
+-- In a subquery that carries an outer reference
+SELECT depname,
+ (SELECT empno FROM empsalary e2
+ WHERE e2.depname = e1.depname
+ QUALIFY row_number() OVER (ORDER BY salary DESC) = 1) AS top_emp
+FROM (SELECT DISTINCT depname FROM empsalary) e1
+ORDER BY depname;
+ depname | top_emp
+-----------+---------
+ develop | 8
+ personnel | 2
+ sales | 1
+(3 rows)
+
+-- Combined with row-level locking (the lock applies to the base table)
+SELECT empno FROM empsalary
+QUALIFY salary > 5000
+ORDER BY empno
+FOR UPDATE;
+ empno
+-------
+ 8
+ 10
+ 11
+(3 rows)
+
+--
+-- Cleanup
+--
+DROP TABLE empsalary;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 8fa0a6c47fb..278554a7307 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -102,7 +102,7 @@ test: publication subscription
# Another group of parallel tests
# select_views depends on create_view
# ----------
-test: select_views portals_p2 foreign_key dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite graph_table
+test: select_views portals_p2 foreign_key dependency guc bitmapops combocid tsearch tsdicts foreign_data window qualify xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite graph_table
# ----------
# Another group of parallel tests (JSON related)
diff --git a/src/test/regress/sql/qualify.sql b/src/test/regress/sql/qualify.sql
new file mode 100644
index 00000000000..c9bf99e23fe
--- /dev/null
+++ b/src/test/regress/sql/qualify.sql
@@ -0,0 +1,563 @@
+--
+-- QUALIFY clause tests
+--
+
+CREATE TEMPORARY TABLE empsalary (
+ depname varchar,
+ empno bigint,
+ salary int,
+ enroll_date date
+);
+
+INSERT INTO empsalary VALUES
+('develop', 10, 5200, '2007-08-01'),
+('sales', 1, 5000, '2006-10-01'),
+('personnel', 5, 3500, '2007-12-10'),
+('sales', 4, 4800, '2007-08-08'),
+('personnel', 2, 3900, '2006-12-23'),
+('develop', 7, 4200, '2008-01-01'),
+('develop', 9, 4500, '2008-01-01'),
+('sales', 3, 4800, '2007-08-01'),
+('develop', 8, 6000, '2006-10-01'),
+('develop', 11, 5200, '2007-08-15');
+
+--
+-- Basic QUALIFY functionality
+--
+
+-- Simple QUALIFY with inline window function
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC, empno;
+
+-- QUALIFY with named window
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2
+ORDER BY depname, salary DESC, empno;
+
+--
+-- Alias resolution tests
+--
+
+-- Reference alias defined in SELECT
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2
+ORDER BY depname, salary DESC, empno;
+
+-- Reference alias with row_number
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+-- Multiple aliases
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2;
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2
+ORDER BY depname, salary DESC;
+
+--
+-- Run condition optimization tests
+--
+
+-- row_number with < operator (should use run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+-- row_number with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+
+-- rank with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+-- dense_rank with = operator (should convert to <= for run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+
+-- count(*) with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+
+--
+-- WHERE pushdown tests
+-- Quals on PARTITION BY columns without window functions can be pushed to WHERE
+--
+
+-- depname is in PARTITION BY, should be pushed to WHERE (SeqScan filter)
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop';
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop'
+ORDER BY salary DESC;
+
+-- Mixed: depname pushed to WHERE, rank condition stays as run condition
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+
+--
+-- QUALIFY without window function in SELECT list
+-- The window function appears only in QUALIFY
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+
+-- With PARTITION BY column filter pushed down
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+
+--
+-- Multiple window functions with different windows
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1;
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1
+ORDER BY depname, empno;
+
+--
+-- QUALIFY with aggregate and window functions
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+
+--
+-- QUALIFY in a grouped query without window functions.
+-- The condition is validated like a SELECT-list item, so aggregates and
+-- grouping columns are allowed (and behave as HAVING would).
+--
+
+-- Aggregate used directly in QUALIFY filters groups like HAVING
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY count(*) > 2
+ORDER BY depname;
+
+-- A grouping column may be referenced directly in QUALIFY
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY depname <> 'sales'
+ORDER BY depname;
+
+--
+-- Comparison with equivalent subquery (results should match)
+--
+
+-- Subquery version
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3;
+
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3
+ORDER BY salary DESC, empno;
+
+-- QUALIFY version (should produce same results)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3
+ORDER BY salary DESC, empno;
+
+--
+-- QUALIFY with different comparison operators
+--
+
+-- Greater than (no run condition optimization for increasing functions)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7
+ORDER BY empno;
+
+-- Equality
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+
+-- BETWEEN (should keep as filter)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5
+ORDER BY empno;
+
+-- IN list
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5);
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5)
+ORDER BY empno;
+
+--
+-- QUALIFY with expressions
+--
+
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+
+--
+-- Error cases
+--
+
+-- Aggregate in QUALIFY without GROUP BY: just as in the SELECT list, the
+-- non-aggregated output columns make this an error (must appear in GROUP BY).
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY sum(salary) > 5000;
+
+-- QUALIFY in a grouped query referencing an ungrouped column (should error,
+-- just as such a reference would in the SELECT list)
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY salary > 100;
+
+-- QUALIFY with set-returning function (should error)
+SELECT empno, salary
+FROM empsalary
+QUALIFY generate_series(1, 3) > 1;
+
+--
+-- QUALIFY in different query structures
+--
+
+-- With DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+
+-- With ORDER BY
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3;
+
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3
+ORDER BY salary DESC, empno;
+
+-- With LIMIT (QUALIFY is evaluated before LIMIT)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+LIMIT 3;
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+ORDER BY salary DESC
+LIMIT 3;
+
+--
+-- Verify evaluation order: QUALIFY happens after window functions, before DISTINCT
+--
+
+-- This should first compute row_number, then filter, then apply DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+
+-- QUALIFY with FILTERS over window function
+EXPLAIN(COSTS OFF) SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+
+SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+
+--
+-- Aggregate functions directly in QUALIFY
+-- (allowed in a grouped query, the same as in the SELECT list / HAVING)
+--
+
+-- Aggregate condition over the group
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000;
+
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000
+ORDER BY depname;
+
+-- Aggregate and window function combined in QUALIFY
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY rank() OVER (ORDER BY sum(salary) DESC) = 1
+ORDER BY depname;
+
+-- Whole-table aggregate (single group)
+SELECT sum(salary) AS s
+FROM empsalary
+QUALIFY sum(salary) > 1000;
+
+--
+-- Name resolution tests
+--
+
+-- An input column takes precedence over a same-named select-list alias
+-- "salary" in QUALIFY is the input column (> 4000 keeps most rows), not the
+-- alias (which is 0 and would keep none)
+SELECT empno, (empno * 0) AS salary
+FROM empsalary
+QUALIFY salary > 4000
+ORDER BY empno;
+
+-- QUALIFY referecing columns that not on output result
+
+-- Same column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY salary;
+
+-- Different column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY enroll_date;
+
+--
+-- Name resolution error cases
+--
+
+-- A non-deterministic alias expression cannot be referenced from QUALIFY
+SELECT empno, (random() < 2)::int AS r
+FROM empsalary
+QUALIFY r = 1;
+
+-- An ambiguous alias reference is rejected
+SELECT empno AS x, salary AS x,
+ row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY x > 0;
+
+-- A name that is neither an input column nor a select-list alias
+SELECT empno
+FROM empsalary
+QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+
+--
+-- QUALIFY without any window function: a general post-SELECT filter
+--
+
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000;
+
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000
+ORDER BY empno;
+
+--
+-- QUALIFY in other query structures
+--
+
+-- In the arms of a set operation
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary) = 1
+UNION ALL
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary DESC) = 1
+ORDER BY empno;
+
+-- In a subquery that carries an outer reference
+SELECT depname,
+ (SELECT empno FROM empsalary e2
+ WHERE e2.depname = e1.depname
+ QUALIFY row_number() OVER (ORDER BY salary DESC) = 1) AS top_emp
+FROM (SELECT DISTINCT depname FROM empsalary) e1
+ORDER BY depname;
+
+-- Combined with row-level locking (the lock applies to the base table)
+SELECT empno FROM empsalary
+QUALIFY salary > 5000
+ORDER BY empno
+FOR UPDATE;
+
+--
+-- Cleanup
+--
+DROP TABLE empsalary;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index c5db6ca6705..04eaaddc685 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2494,6 +2494,9 @@ QTNode
QUERYTYPE
QualCost
QualItem
+QualifyExtractContext
+QualifyHookState
+QualifyVarmapContext
Query
QueryCompletion
QueryDesc
--
2.50.1 (Apple Git-155)
v2-0001-Add-QUALIFY-clause.patch.nocfbot (text/plain, 86.3K) download
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-29 00:46 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 09:48 ` Re: Proposal: QUALIFY clause Richard Guo <guofenglinux@gmail.com>
2026-06-29 14:41 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2026-07-14 18:23 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-09-24 13:06 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2026-07-14 18:23 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Vik Fearing <vik@postgresfriends.org>; Marcos Pegoraro <marcos@f10.com.br>; Peter Eisentraut <peter@eisentraut.org>; Richard Guo <guofenglinux@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>
On Mon Jun 29, 2026 at 11:41 AM -03, Matheus Alcantara wrote:
> The big win of the rewrite approach is that the planner already
> optimizes window functions sitting inside a subquery, so QUALIFY gets
> those optimizations (window run conditions and pushing quals down below
> the WindowAgg) for free, with no new planner code. The plans come out
> identical to the equivalent hand-written subquery.
>
> The main downside is view deparse: because the stored query is the
> rewritten subquery, pg_get_viewdef() of a view defined with QUALIFY
> shows the subquery form rather than the QUALIFY keyword.
>
> An alternative:
>
> Another approach is to teach the planner about QUALIFY directly and
> apply the same window optimizations to its quals. I'm attaching a second
> patch (v2-0001-Add-QUALIFY-clause.patch.nocfbot) that does this, but
> only for the window-function case. Since QUALIFY is a general
> post-SELECT filter, a condition that doesn't reference a window function
> would, in this approach, need a gating Result node carrying the QUALIFY
> filter on top of the plan tree; that part is not implemented in this
> patch. This approach keeps QUALIFY first-class (clean view deparse, no
> synthetic subquery), at the cost of duplicating the run-condition and
> qual-pushdown logic that today lives at the subquery boundary.
>
When I wrote this I hadn't looked closely at ExecResult and I assumed a
Result node could carry a filter qual and just skip non-matching rows,
but that turns out not to be the case. ExecResult only checks
resconstantqual once, for the LIMIT 0-style case; it never loops
re-fetching from its outer plan until a per-row qual passes, the way
ExecScan does for every Scan node, or the way Agg/WindowAgg do by hand
for HAVING and window run conditions.
I looked at how DuckDB implements QUALIFY and it has a physical Filter
operator, also used for WHERE, and QUALIFY just puts one on top of the
window operator.
Postgres doesn't have an equivalent generic node. We filter rows
everywhere, but always as a capability built into a specific node type.
There's no node whose sole job is "filter an arbitrary already-computed
row stream," which is what QUALIFY needs for the case where its
condition doesn't reference a window function at all. So I'm thinking
about two options: teach ExecResult a real per-row filter loop, or
introduce a dedicated node for this purpose.
Either way, the cases where we'd actually need this node are narrower
than "QUALIFY without a window function." A QUALIFY condition that
doesn't reference a window function, in a query that has no window
functions at all, can be pushed into WHERE - mirroring the existing
optimization that moves a HAVING clause with no aggregates into WHERE.
And when window functions are present, a condition is still safe to push
below them as long as it only references columns that are in every
window clause's PARTITION BY list, the same rule that already handle
pushing quals below a WindowAgg. So the generic node is only strictly
needed when a QUALIFY condition references a window function's result in
a way that can't become a run condition, or references plain columns
that aren't common to every partition i.e., the cases that don't
reduce to either WHERE-pushdown or the WindowAgg qual. I'm just
wondering, though, whether either implementation option would be useful
beyond QUALIFY, I'm not sure it's worth building either just for this
one clause.
> So there are two patches attached:
>
> - v2-0001-Add-QUALIFY-clause.patch: the query-rewrite approach, complete (window and
> non-window QUALIFY), with docs and tests.
>
> - v2-0001-Add-QUALIFY-clause.patch.nocfbot: the planner-based approach,
> window-functions only. Note that there is some test cases failing due
> to WIP state.
>
CFBot was not happy with v2 due to some compiler warnings. Attaching v3
with fixes, not major changes compared with v2.
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
Attachments:
v3-0001-Add-QUALIFY-clause.patch (text/plain, 85.8K) download
From 45df6c66095a22839feca01e7d764c9252584ed2 Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <mths.dev@pm.me>
Date: Mon, 29 Jun 2026 10:49:43 -0300
Subject: [PATCH v3] Add QUALIFY clause
QUALIFY filters rows using the result of a window function without
requiring the query to be wrapped in a subquery or CTE. It is to window
functions what HAVING is to aggregates: a post-SELECT filter, evaluated
after the window functions have been computed but before DISTINCT, ORDER
BY, and LIMIT. The condition may contain window functions directly,
whether or not they also appear in the select list, and it may reference
select-list output names, which are not visible to WHERE or HAVING.
The clause is implemented in the parser by rewriting a query
specification that carries a QUALIFY clause into an equivalent two-level
query: an inner subquery holding the table expression and select list,
wrapped by an outer query whose WHERE clause is the QUALIFY condition.
This follows the syntactic transformation described in the SQL standard
change proposal. Because the planner already optimizes window functions
that appear inside a subquery, the rewritten form obtains window run
conditions and quals pushdown without any new planner code, producing
plans identical to those of the equivalent hand-written subquery.
The condition is transformed in the scope of the inner query, so a name
that refers to a column of the FROM tables resolves to that column in
preference to a select-list alias of the same name. Window functions,
aggregates, and inner columns referenced by the condition are projected
through the subquery and referenced from the outer WHERE clause by Vars
nodes, which preserves the comparison shape that the run-condition
machinery recognizes. Because QUALIFY is evaluated after the select
list, the ORDER BY, DISTINCT, and LIMIT clauses are processed against
the outer query.
QUALIFY is added as a reserved keyword, as required by the standard.
---
doc/src/sgml/ref/select.sgml | 99 +++
src/backend/nodes/nodeFuncs.c | 2 +
src/backend/parser/analyze.c | 504 +++++++++++
src/backend/parser/gram.y | 16 +-
src/backend/parser/parse_agg.c | 4 +
src/backend/parser/parse_expr.c | 4 +
src/backend/parser/parse_func.c | 3 +
src/include/nodes/parsenodes.h | 1 +
src/include/parser/kwlist.h | 1 +
src/include/parser/parse_node.h | 1 +
src/test/regress/expected/qualify.out | 1122 +++++++++++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/qualify.sql | 563 +++++++++++++
src/tools/pgindent/typedefs.list | 3 +
14 files changed, 2320 insertions(+), 5 deletions(-)
create mode 100644 src/test/regress/expected/qualify.out
create mode 100644 src/test/regress/sql/qualify.sql
diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml
index 8d5a751af7e..41c3aac5fbb 100644
--- a/doc/src/sgml/ref/select.sgml
+++ b/doc/src/sgml/ref/select.sgml
@@ -40,6 +40,7 @@ SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replac
[ GROUP BY { ALL | [ ALL | DISTINCT ] <replaceable class="parameter">grouping_element</replaceable> [, ...] } ]
[ HAVING <replaceable class="parameter">condition</replaceable> ]
[ WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] ]
+ [ QUALIFY <replaceable class="parameter">condition</replaceable> ]
[ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class="parameter">select</replaceable> ]
[ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]
[ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ]
@@ -146,6 +147,16 @@ TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]
</para>
</listitem>
+ <listitem>
+ <para>
+ If the <literal>QUALIFY</literal> clause is specified, all rows
+ that do not satisfy the condition are eliminated from the output.
+ Because <literal>QUALIFY</literal> is applied after the output rows
+ have been computed, its condition can reference window functions
+ and output column names. (See <xref linkend="sql-qualify"/> below.)
+ </para>
+ </listitem>
+
<listitem>
<para><literal>SELECT DISTINCT</literal> eliminates duplicate rows from the
result. <literal>SELECT DISTINCT ON</literal> eliminates rows that
@@ -1243,6 +1254,83 @@ EXCLUDE NO OTHERS
</note>
</refsect2>
+ <refsect2 id="sql-qualify" xreflabel="QUALIFY Clause">
+ <title><literal>QUALIFY</literal> Clause</title>
+
+ <para>
+ The optional <literal>QUALIFY</literal> clause has the general form
+<synopsis>
+QUALIFY <replaceable class="parameter">condition</replaceable>
+</synopsis>
+ where <replaceable class="parameter">condition</replaceable> is
+ any expression that evaluates to a result of type
+ <type>boolean</type>, the same as specified for the
+ <literal>WHERE</literal> clause.
+ </para>
+
+ <para>
+ <literal>QUALIFY</literal> eliminates rows that do not satisfy the
+ condition. It is applied after window functions have been computed,
+ so its condition may refer to the results of window functions. In
+ this respect <literal>QUALIFY</literal> is to window functions what
+ <link linkend="sql-having"><literal>HAVING</literal></link> is to
+ aggregate functions: each filters the result of its corresponding
+ computation stage. Without <literal>QUALIFY</literal>, filtering on
+ the result of a window function requires wrapping the query in a
+ sub-query (or common table expression) and applying a
+ <literal>WHERE</literal> clause there, because window functions are
+ computed after <literal>WHERE</literal> and <literal>HAVING</literal>.
+ A row is retained only if the condition evaluates to true; rows for
+ which it evaluates to false or null are eliminated.
+ </para>
+
+ <para>
+ The condition may contain window functions, whether or not the same
+ window functions also appear in the <command>SELECT</command> list.
+ These window functions may use an inline <literal>OVER</literal>
+ clause or refer to a window defined in the
+ <link linkend="sql-window"><literal>WINDOW</literal></link> clause; a
+ <literal>WINDOW</literal> clause is not required. Because
+ <literal>QUALIFY</literal> is evaluated after the
+ <command>SELECT</command> list, the condition may also reference
+ output column names (column aliases defined in the
+ <command>SELECT</command> list), unlike <literal>WHERE</literal> and
+ <literal>HAVING</literal>. In case of ambiguity, a name in
+ <literal>QUALIFY</literal> is interpreted as an input-column name
+ rather than an output column name.
+ </para>
+
+ <para>
+ <literal>QUALIFY</literal> does not require window functions to be
+ present; it is a general filter applied to the computed output rows.
+ A condition that does not involve a window function and refers only to
+ input columns produces the same result as if it had been written in
+ <literal>WHERE</literal>, though writing such conditions in
+ <literal>WHERE</literal> is preferred. Aggregate functions are
+ permitted in the condition under the same rules that apply to the
+ <command>SELECT</command> list, since aggregation has already occurred
+ by the time <literal>QUALIFY</literal> is evaluated.
+ </para>
+
+ <para>
+ The following query returns, for each department, only the
+ highest-paid employees, filtering on the result of a window function
+ without a sub-query:
+<programlisting>
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS pos
+FROM empsalary
+QUALIFY pos = 1;
+</programlisting>
+ Here the output column name <literal>pos</literal> defined in the
+ <command>SELECT</command> list is referenced in
+ <literal>QUALIFY</literal>. The window function could equally be
+ spelled out in the <literal>QUALIFY</literal> condition itself, in
+ which case it need not appear in the <command>SELECT</command> list at
+ all.
+ </para>
+ </refsect2>
+
<refsect2 id="sql-distinct" xreflabel="DISTINCT Clause">
<title><literal>DISTINCT</literal> Clause</title>
@@ -2046,6 +2134,17 @@ FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
missing features.
</para>
+ <refsect2>
+ <title>The <literal>QUALIFY</literal> Clause</title>
+
+ <para>
+ The <literal>QUALIFY</literal> clause conforms to the SQL standard
+ (feature O001, <quote>QUALIFY clause</quote>). Note that
+ <literal>QUALIFY</literal> is a reserved word; existing applications
+ that use it as an identifier must quote it or choose another name.
+ </para>
+ </refsect2>
+
<refsect2>
<title>Omitted <literal>FROM</literal> Clauses</title>
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 2a2e00b372e..36cae30c0b3 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -4488,6 +4488,8 @@ raw_expression_tree_walker_impl(Node *node,
return true;
if (WALK(stmt->rarg))
return true;
+ if (WALK(stmt->qualifyClause))
+ return true;
}
break;
case T_PLAssignStmt:
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index ea97d236ea8..7824b51c476 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -52,6 +52,7 @@
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
+#include "rewrite/rewriteManip.h"
#include "utils/backend_status.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
@@ -70,6 +71,31 @@ typedef struct SelectStmtPassthrough
List *indirection; /* indirection yet to be applied to target */
} SelectStmtPassthrough;
+/* State for the QUALIFY select-list alias resolution hook */
+typedef struct QualifyHookState
+{
+ List *targetList; /* target list to match aliases against */
+ PostParseColumnRefHook prev_hook; /* previously installed hook, if any */
+ void *prev_hook_state; /* its state */
+} QualifyHookState;
+
+/* Working state for qualifyExtractMutator */
+typedef struct QualifyExtractContext
+{
+ List **innerTargetList; /* inner query's target list (appended to) */
+ int subquery_varno; /* varno of the subquery RTE in the outer
+ * query */
+ int next_resno; /* next resno to assign to appended entries */
+} QualifyExtractContext;
+
+/* Working state for qualifyFixupVarattno */
+typedef struct QualifyVarmapContext
+{
+ int subquery_varno; /* varno whose Vars are to be remapped */
+ AttrNumber *attmap; /* map from old resno to new resno */
+} QualifyVarmapContext;
+
+
/* Hook for plugins to get control at end of parse analysis */
post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
@@ -108,6 +134,10 @@ static Query *transformCallStmt(ParseState *pstate,
CallStmt *stmt);
static void transformLockingClause(ParseState *pstate, Query *qry,
LockingClause *lc, bool pushedDown);
+static Node *qualifyPostColumnRefHook(ParseState *pstate, ColumnRef *cref,
+ Node *var);
+static Query *rewriteQualifyQuery(ParseState *pstate, Query *innerQuery,
+ Node *qualifyExpr);
#ifdef DEBUG_NODE_TESTS_ENABLED
static bool test_raw_expression_coverage(Node *node, void *context);
#endif
@@ -1724,6 +1754,427 @@ count_rowexpr_columns(ParseState *pstate, Node *expr)
return -1;
}
+/*
+ * qualifyPostColumnRefHook
+ * Resolve a QUALIFY column references
+ *
+ * QUALIFY column references can reference table columns and target alias. A
+ * real column of the FROM tables take precedence over a select-list alias of
+ * the same name.
+ */
+static Node *
+qualifyPostColumnRefHook(ParseState *pstate, ColumnRef *cref, Node *var)
+{
+ QualifyHookState *qstate = (QualifyHookState *) pstate->p_ref_hook_state;
+ char *name;
+ TargetEntry *matched = NULL;
+ ListCell *lc;
+
+ /* A real column of the FROM tables takes precedence over an alias. */
+ if (var != NULL)
+ return NULL;
+
+ /* Only unqualified (single-field) names can match a select-list alias. */
+ if (list_length(cref->fields) != 1 || !IsA(linitial(cref->fields), String))
+ return NULL;
+
+ name = strVal(linitial(cref->fields));
+
+ foreach(lc, qstate->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resjunk || tle->resname == NULL || strcmp(tle->resname, name) != 0)
+ continue;
+
+ if (matched != NULL && !equal(matched->expr, tle->expr))
+ ereport(ERROR,
+ (errcode(ERRCODE_AMBIGUOUS_COLUMN),
+ errmsg("column reference \"%s\" is ambiguous", name),
+ parser_errposition(pstate, cref->location)));
+ matched = tle;
+ }
+
+ if (matched == NULL)
+ return NULL;
+
+ /*
+ * XXX: an alias whose expression is non-deterministic would be evaluated
+ * once for the select-list column and again in the outer filter built
+ * from the QUALIFY condition, possibly producing different values. Until
+ * such references are resolved by the identity of the select-list entry
+ * (projecting it once and referencing it by a single Var), reject
+ * volatile alias expressions.
+ */
+ if (contain_volatile_functions((Node *) matched->expr))
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("QUALIFY cannot reference output column \"%s\" whose expression is non-deterministic",
+ name),
+ parser_errposition(pstate, cref->location)));
+
+ return copyObject((Node*) matched->expr);
+}
+
+/*
+ * qualifyExtractMutator
+ * Rewrite a QUALIFY condition so it can serve as the WHERE clause of the
+ * outer query built by rewriteQualifyQuery.
+ *
+ * Every window function, aggregate, and Var of the inner query is computed by
+ * the inner query and referenced from the outer query by a plain Var: we find
+ * an existing target entry with an equal expression, or append a new resjunk
+ * one, and replace the node with an outer Var. Comparisons and other
+ * operators are left in place at the outer level. This reproduces the shape
+ * of a hand-written subquery, so the planner's existing optimizations for
+ * window functions in subqueries (run conditions and qual pushdown) apply
+ * unchanged.
+ */
+static Node *
+qualifyExtractMutator(Node *node, QualifyExtractContext *ctx)
+{
+ if (node == NULL)
+ return NULL;
+
+ if (IsA(node, WindowFunc) || IsA(node, Aggref)
+ || (IsA(node, Var) && ((Var *) node)->varlevelsup == 0))
+ {
+ TargetEntry *tle = NULL;
+
+ /* Reuse a matching target entry so a value isn't projected twice. */
+ foreach_ptr(TargetEntry, cur, *ctx->innerTargetList)
+ {
+ if (equal(cur->expr, node))
+ {
+ tle = cur;
+ break;
+ }
+ }
+
+ /*
+ * Did not find the target entry on target list so add it on inner
+ * query target list so it can be referenced on the outer query.
+ */
+ if (tle == NULL)
+ {
+ tle = makeTargetEntry((Expr *) copyObject(node),
+ ctx->next_resno++,
+ NULL,
+ false);
+ *ctx->innerTargetList = lappend(*ctx->innerTargetList, tle);
+ }
+
+ /*
+ * The entry is referenced from the outer query, so it must be a real
+ * (non-resjunk) output column of the subquery. A reused entry might
+ * be a resjunk grouping column or a junk ORDER BY/DISTINCT target, so
+ * clear the flag here.
+ */
+ tle->resjunk = false;
+
+ return (Node *) makeVarFromTargetEntry(ctx->subquery_varno, tle);
+ }
+
+ return expression_tree_mutator(node, qualifyExtractMutator, ctx);
+}
+
+/*
+ * qualifyFixupVarattno
+ * Remap the attribute numbers of Vars referencing the QUALIFY subquery,
+ * after the subquery's target list has been renumbered.
+ */
+static bool
+qualifyFixupVarattno(Node *node, QualifyVarmapContext *ctx)
+{
+ if (node == NULL)
+ return false;
+
+ if (IsA(node, Var))
+ {
+ Var *var = (Var *) node;
+
+ if (var->varlevelsup == 0 && var->varno == ctx->subquery_varno)
+ {
+ var->varattno = ctx->attmap[var->varattno];
+ var->varattnosyn = var->varattno;
+ }
+ return false;
+ }
+
+ return expression_tree_walker(node, qualifyFixupVarattno, ctx);
+}
+
+/*
+ * rewriteQualifyQuery
+ * Implement the QUALIFY clause by rewriting the inner query in an outer
+ * query whose WHERE clause is the QUALIFY condition.
+ *
+ * 'innerQuery' is the fully-analyzed query for the table expression and select
+ * list, with the resolved QUALIFY condition appended to its target list as a
+ * resjunk entry. We remove that entry, decompose the condition into the outer
+ * WHERE clause (extracting window functions, aggregates, and inner Vars into
+ * the inner target list), and process the deferred ORDER BY, DISTINCT, and
+ * LIMIT clauses against the outer query.
+ */
+static Query *
+rewriteQualifyQuery(ParseState *pstate, Query *innerQuery, Node *qualifyExpr)
+{
+ Query *outerQuery = makeNode(Query);
+ List *outerTargetList = NIL;
+ List *origTargetList = NIL;
+ List *nonjunk = NIL;
+ List *junk = NIL;
+ Bitmapset *liftrefs = NULL;
+ ParseState *opstate;
+ ParseNamespaceItem *nsitem;
+ QualifyExtractContext ctx;
+ Node *outerQual;
+ List *outerSortClause;
+ List *outerDistinctClause;
+ bool outerHasDistinctOn;
+ Node *outerLimitOffset;
+ Node *outerLimitCount;
+ LimitOption outerLimitOption;
+ ListCell *lc;
+ int resno;
+ int ntargets;
+ AttrNumber *attmap;
+ QualifyVarmapContext mapctx;
+ AttrNumber newresno;
+
+ /*
+ * ORDER BY, DISTINCT, and LIMIT were transformed against the inner
+ * query's scope but are logically evaluated after QUALIFY, so they move
+ * to the outer query. Detach them from the inner query; the sort and
+ * distinct clauses are re-attached below after the columns they reference
+ * are exposed as subquery outputs.
+ */
+ outerSortClause = innerQuery->sortClause;
+ outerDistinctClause = innerQuery->distinctClause;
+ outerHasDistinctOn = innerQuery->hasDistinctOn;
+ outerLimitOffset = innerQuery->limitOffset;
+ outerLimitCount = innerQuery->limitCount;
+ outerLimitOption = innerQuery->limitOption;
+ innerQuery->sortClause = NIL;
+ innerQuery->distinctClause = NIL;
+ innerQuery->hasDistinctOn = false;
+ innerQuery->limitOffset = NULL;
+ innerQuery->limitCount = NULL;
+ innerQuery->limitOption = LIMIT_OPTION_COUNT;
+
+ /* Collect the sort/group refs that the lifted ORDER BY / DISTINCT use. */
+ foreach(lc, outerSortClause)
+ liftrefs = bms_add_member(liftrefs,
+ ((SortGroupClause *) lfirst(lc))->tleSortGroupRef);
+ foreach(lc, outerDistinctClause)
+ liftrefs = bms_add_member(liftrefs,
+ ((SortGroupClause *) lfirst(lc))->tleSortGroupRef);
+
+ /*
+ * Remove the temporary resjunk QUALIFY entry from the inner target list
+ * required by parseCheckAggregates.
+ */
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->expr == (Expr *) qualifyExpr)
+ {
+ Assert(tle->resjunk);
+ innerQuery->targetList = foreach_delete_current(innerQuery->targetList, lc);
+ break;
+ }
+ }
+
+ /*
+ * Capture the original select-list output columns now, before extraction
+ * and lifting may append further (non-resjunk) columns or un-junk
+ * grouping/sort columns; these are what the outer query projects.
+ */
+ foreach_ptr(TargetEntry, tle, innerQuery->targetList)
+ {
+ if (!tle->resjunk)
+ origTargetList = lappend(origTargetList, tle);
+ }
+
+ /*
+ * Extract the QUALIFY condition into the outer WHERE clause, projecting
+ * the inner-query expressions it needs through the subquery. The subquery
+ * will be range-table entry 1 of the outer query.
+ */
+ ctx.innerTargetList = &innerQuery->targetList;
+ ctx.subquery_varno = 1;
+ ctx.next_resno = list_length(innerQuery->targetList) + 1;
+ outerQual = qualifyExtractMutator(qualifyExpr, &ctx);
+
+ /*
+ * Expose as non-resjunk subquery outputs, the inner columns that the
+ * lifted ORDER BY / DISTINCT clauses reference, so the outer query can
+ * refer to them. Grouping columns not referenced by ORDER BY/DISTINCT
+ * stay resjunk.
+ */
+ foreach_ptr(TargetEntry, tle, innerQuery->targetList)
+ {
+ if (tle->ressortgroupref != 0 && bms_is_member(tle->ressortgroupref, liftrefs))
+ tle->resjunk = false;
+ }
+
+ /*
+ * A subquery range table entry requires its non-resjunk columns to come
+ * first with contiguous resnos, and every output column must have a name.
+ * Reorder the inner target list accordingly, name any anonymous output
+ * columns, and remap the resnos referenced by the outer WHERE clause.
+ */
+ ntargets = list_length(innerQuery->targetList);
+ attmap = (AttrNumber *) palloc0((ntargets + 1) * sizeof(AttrNumber));
+
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resjunk)
+ junk = lappend(junk, tle);
+ else
+ nonjunk = lappend(nonjunk, tle);
+ }
+ innerQuery->targetList = list_concat(nonjunk, junk);
+
+ newresno = 1;
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ attmap[tle->resno] = newresno;
+ tle->resno = newresno;
+
+ /*
+ * Output columns created by extraction are anonymous. Give a Var the
+ * name of its source column, so the lifted ORDER BY/DISTINCT and the
+ * outer WHERE can reference an input column (e.g. "QUALIFY x > 0
+ * ORDER BY x"); fall back to a generated name for non-Var
+ * expressions.
+ */
+ if (!tle->resjunk && tle->resname == NULL)
+ {
+ if (IsA(tle->expr, Var) && ((Var *) tle->expr)->varattno > 0)
+ {
+ Var *var = (Var *) tle->expr;
+
+ tle->resname = get_rte_attribute_name(rt_fetch(var->varno,
+ innerQuery->rtable),
+ var->varattno);
+ }
+ if (tle->resname == NULL)
+ tle->resname = psprintf("qualify%d", newresno);
+ }
+ newresno++;
+ }
+
+ /* Now fix the QUALIFY Var references */
+ mapctx.subquery_varno = ctx.subquery_varno;
+ mapctx.attmap = attmap;
+ qualifyFixupVarattno(outerQual, &mapctx);
+
+ /*
+ * The inner query is now one level deeper than it was, so bump the level
+ * of any outer references it contains. The outer WHERE clause (and the
+ * lifted clauses) stay at the current level.
+ */
+ IncrementVarSublevelsUp((Node *) innerQuery, 1, 1);
+
+ /* Build the outer query's parse state, sharing the original parent. */
+ opstate = make_parsestate(pstate->parentParseState);
+ opstate->p_sourcetext = pstate->p_sourcetext;
+ opstate->p_pre_columnref_hook = pstate->p_pre_columnref_hook;
+ opstate->p_post_columnref_hook = pstate->p_post_columnref_hook;
+ opstate->p_paramref_hook = pstate->p_paramref_hook;
+ opstate->p_coerce_param_hook = pstate->p_coerce_param_hook;
+ opstate->p_ref_hook_state = pstate->p_ref_hook_state;
+
+ outerQuery->commandType = CMD_SELECT;
+
+ nsitem = addRangeTableEntryForSubquery(opstate, innerQuery,
+ makeAlias("pg_qualify", NIL),
+ false, true);
+ addNSItemToQuery(opstate, nsitem, true, true, true);
+
+ /* Outer target list: project the original select-list output columns. */
+ resno = 1;
+ foreach(lc, origTargetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+ Var *var = makeVarFromTargetEntry(ctx.subquery_varno, tle);
+
+ outerTargetList = lappend(outerTargetList,
+ makeTargetEntry((Expr *) var,
+ resno++,
+ tle->resname ? pstrdup(tle->resname) : NULL,
+ false));
+ }
+
+ /*
+ * Re-attach the lifted ORDER BY / DISTINCT clauses. For each inner
+ * column they reference, give the outer target that projects it the same
+ * sort/ group ref so the moved SortGroupClauses line up; a referenced
+ * column not in the projection gets a resjunk outer target.
+ */
+ foreach_ptr(TargetEntry, innerTle, innerQuery->targetList)
+ {
+ TargetEntry *out = NULL;
+
+ if (innerTle->ressortgroupref == 0 || !bms_is_member(innerTle->ressortgroupref, liftrefs))
+ continue;
+
+ foreach_ptr(TargetEntry, outerTle, outerTargetList)
+ {
+
+ if (IsA(outerTle->expr, Var) && ((Var *) outerTle->expr)->varattno == innerTle->resno)
+ {
+ out = outerTle;
+ break;
+ }
+ }
+
+ if (out == NULL)
+ {
+ Var *var = makeVarFromTargetEntry(ctx.subquery_varno, innerTle);
+
+ out = makeTargetEntry((Expr *) var,
+ resno++,
+ innerTle->resname ? pstrdup(innerTle->resname) : NULL,
+ true);
+ outerTargetList = lappend(outerTargetList, out);
+ }
+ out->ressortgroupref = innerTle->ressortgroupref;
+ }
+
+ outerQuery->targetList = outerTargetList;
+ outerQuery->rtable = opstate->p_rtable;
+ outerQuery->rteperminfos = opstate->p_rteperminfos;
+ outerQuery->jointree = makeFromExpr(opstate->p_joinlist, outerQual);
+
+ outerQuery->sortClause = outerSortClause;
+ outerQuery->distinctClause = outerDistinctClause;
+ outerQuery->hasDistinctOn = outerHasDistinctOn;
+ outerQuery->limitOffset = outerLimitOffset;
+ outerQuery->limitCount = outerLimitCount;
+ outerQuery->limitOption = outerLimitOption;
+
+ /*
+ * The outer query has no aggregates or window functions (those were
+ * extracted into the subquery), so only sub-links need to be reported.
+ */
+ outerQuery->hasSubLinks = checkExprHasSubLink(outerQual) ||
+ checkExprHasSubLink(outerLimitOffset) ||
+ checkExprHasSubLink(outerLimitCount);
+
+ assign_query_collations(opstate, outerQuery);
+
+ free_parsestate(opstate);
+
+ return outerQuery;
+}
+
/*
* transformSelectStmt -
@@ -1746,6 +2197,8 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
Query *qry = makeNode(Query);
Node *qual;
ListCell *l;
+ bool hasQualify = (stmt->qualifyClause != NULL);
+ Node *qualifyExpr = NULL;
qry->commandType = CMD_SELECT;
@@ -1802,6 +2255,13 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
* transformGroupClause and transformDistinctClause need the results. Note
* that these functions can also change the targetList, so it's passed to
* them by reference.
+ *
+ * When a QUALIFY clause is present, ORDER BY/DISTINCT/LIMIT are logically
+ * evaluated after QUALIFY and so belong to the outer query that
+ * rewriteQualifyQuery() builds. We still transform them here, against
+ * the inner query's scope, so that they can reference input columns and
+ * select-list aliases as in any other query; rewriteQualifyQuery() then
+ * lifts the resulting clauses out to the outer query.
*/
qry->sortClause = transformSortClause(pstate,
stmt->sortClause,
@@ -1853,6 +2313,42 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
stmt->limitOption);
qry->limitOption = stmt->limitOption;
+ /*
+ * Transform the QUALIFY condition, if any. This must happen before
+ * transformWindowDefinitions() so that window functions appearing only in
+ * QUALIFY get their inline window specifications registered and turned
+ * into WindowClauses. QUALIFY may reference select-list aliases, so we
+ * install a post-columnref hook that resolves a bare name to a
+ * select-list alias.
+ *
+ * The resolved condition is appended to the target list as a resjunk
+ * entry so that parseCheckAggregates() validates it like a select-list
+ * item; it is removed and decomposed into the outer query's WHERE clause
+ * by rewriteQualifyQuery() below.
+ */
+ if (hasQualify)
+ {
+ QualifyHookState qstate;
+
+ qstate.targetList = qry->targetList;
+ qstate.prev_hook = pstate->p_post_columnref_hook;
+ qstate.prev_hook_state = pstate->p_ref_hook_state;
+ pstate->p_post_columnref_hook = qualifyPostColumnRefHook;
+ pstate->p_ref_hook_state = &qstate;
+
+ qualifyExpr = transformWhereClause(pstate, stmt->qualifyClause,
+ EXPR_KIND_QUALIFY, "QUALIFY");
+
+ pstate->p_post_columnref_hook = qstate.prev_hook;
+ pstate->p_ref_hook_state = qstate.prev_hook_state;
+
+ qry->targetList = lappend(qry->targetList,
+ makeTargetEntry((Expr *) qualifyExpr,
+ list_length(qry->targetList) + 1,
+ NULL,
+ true));
+ }
+
/* transform window clauses after we have seen all window functions */
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
@@ -1883,6 +2379,14 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
parseCheckAggregates(pstate, qry);
+ /*
+ * If a QUALIFY clause was present, wrap the query just built (the inner
+ * query) in an outer query whose WHERE clause is the QUALIFY condition,
+ * and process the deferred ORDER BY/DISTINCT/LIMIT clauses against it.
+ */
+ if (hasQualify)
+ return rewriteQualifyQuery(pstate, qry, qualifyExpr);
+
return qry;
}
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 9e05a314707..86c95a8b8cb 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -532,7 +532,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <node> TableElement TypedTableElement ConstraintElem DomainConstraintElem TableFuncElement
%type <node> columnDef columnOptions optionalPeriodName
%type <defelt> def_elem reloption_elem old_aggr_elem operator_def_elem
-%type <node> def_arg columnElem where_clause where_or_current_clause
+%type <node> def_arg columnElem where_clause qualify_clause where_or_current_clause
a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound
columnref having_clause func_table xmltable array_expr
OptWhereClause operator_def_arg
@@ -817,7 +817,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PROPERTIES PROPERTY PUBLICATION
- QUOTE QUOTES
+ QUALIFY QUOTE QUOTES
RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING
REFRESH REINDEX RELATIONSHIP RELATIVE_P RELEASE RENAME REPACK REPEATABLE REPLACE REPLICA
@@ -13752,7 +13752,7 @@ select_clause:
simple_select:
SELECT opt_all_clause opt_target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13765,11 +13765,12 @@ simple_select:
n->groupByAll = ($7)->all;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| SELECT distinct_clause target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13783,6 +13784,7 @@ simple_select:
n->groupByAll = ($7)->all;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| values_clause { $$ = $1; }
@@ -14970,6 +14972,11 @@ where_clause:
| /*EMPTY*/ { $$ = NULL; }
;
+qualify_clause:
+ QUALIFY a_expr { $$ = $2; }
+ | /*EMPTY*/ { $$ = NULL; }
+ ;
+
/* variant for UPDATE and DELETE */
where_or_current_clause:
WHERE a_expr { $$ = $2; }
@@ -19435,6 +19442,7 @@ reserved_keyword:
| ORDER
| PLACING
| PRIMARY
+ | QUALIFY
| REFERENCES
| RETURNING
| SELECT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index acb933392de..8153b074e55 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -407,6 +407,9 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ /* okay */
+ break;
case EXPR_KIND_POLICY:
if (isAgg)
err = _("aggregate functions are not allowed in policy expressions");
@@ -964,6 +967,7 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
err = _("window functions are not allowed in window definitions");
break;
case EXPR_KIND_SELECT_TARGET:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index e6ea34a7809..0d80512bee1 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -579,6 +579,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_GENERATED_COLUMN:
case EXPR_KIND_CYCLE_MARK:
case EXPR_KIND_PROPGRAPH_PROPERTY:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
@@ -1820,6 +1821,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FROM_SUBSELECT:
case EXPR_KIND_FROM_FUNCTION:
case EXPR_KIND_WHERE:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
case EXPR_KIND_FILTER:
@@ -3180,6 +3182,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "function in FROM";
case EXPR_KIND_WHERE:
return "WHERE";
+ case EXPR_KIND_QUALIFY:
+ return "QUALIFY";
case EXPR_KIND_POLICY:
return "POLICY";
case EXPR_KIND_HAVING:
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index a9b6be7203b..bbcec777024 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -2689,6 +2689,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
err = _("set-returning functions are not allowed in policy expressions");
break;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 77f69f94607..55054e0693a 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -2344,6 +2344,7 @@ typedef struct SelectStmt
bool groupByAll; /* Is this GROUP BY ALL? */
Node *havingClause; /* HAVING conditional-expression */
List *windowClause; /* WINDOW window_name AS (...), ... */
+ Node *qualifyClause; /* QUALIFY conditional-expression */
/*
* In a "leaf" node representing a VALUES list, the above fields are all
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 51ead54f015..a83545931c1 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -370,6 +370,7 @@ PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("properties", PROPERTIES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("property", PROPERTY, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("qualify", QUALIFY, RESERVED_KEYWORD, AS_LABEL)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("quotes", QUOTES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f7f4ba6c2a8..2443a1192d4 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -45,6 +45,7 @@ typedef enum ParseExprKind
EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
EXPR_KIND_WHERE, /* WHERE */
EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_QUALIFY, /* QUALIFY */
EXPR_KIND_FILTER, /* FILTER */
EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
diff --git a/src/test/regress/expected/qualify.out b/src/test/regress/expected/qualify.out
new file mode 100644
index 00000000000..ae55a556449
--- /dev/null
+++ b/src/test/regress/expected/qualify.out
@@ -0,0 +1,1122 @@
+--
+-- QUALIFY clause tests
+--
+CREATE TEMPORARY TABLE empsalary (
+ depname varchar,
+ empno bigint,
+ salary int,
+ enroll_date date
+);
+INSERT INTO empsalary VALUES
+('develop', 10, 5200, '2007-08-01'),
+('sales', 1, 5000, '2006-10-01'),
+('personnel', 5, 3500, '2007-12-10'),
+('sales', 4, 4800, '2007-08-08'),
+('personnel', 2, 3900, '2006-12-23'),
+('develop', 7, 4200, '2008-01-01'),
+('develop', 9, 4500, '2008-01-01'),
+('sales', 3, 4800, '2007-08-01'),
+('develop', 8, 6000, '2006-10-01'),
+('develop', 11, 5200, '2007-08-15');
+--
+-- Basic QUALIFY functionality
+--
+-- Simple QUALIFY with inline window function
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rank
+-----------+-------+--------+------
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+-- QUALIFY with named window
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rank
+-----------+-------+--------+------
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+--
+-- Alias resolution tests
+--
+-- Reference alias defined in SELECT
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rnk
+-----------+-------+--------+-----
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+-- Reference alias with row_number
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 < 3)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- Multiple aliases
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: ((pg_qualify.rn = 1) OR (pg_qualify.rnk <= 2))
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2
+ORDER BY depname, salary DESC;
+ depname | empno | salary | rn | rnk
+-----------+-------+--------+----+-----
+ develop | 8 | 6000 | 1 | 1
+ develop | 10 | 5200 | 2 | 2
+ develop | 11 | 5200 | 3 | 2
+ personnel | 2 | 3900 | 1 | 1
+ personnel | 5 | 3500 | 2 | 2
+ sales | 1 | 5000 | 1 | 1
+ sales | 4 | 4800 | 2 | 2
+ sales | 3 | 4800 | 3 | 2
+(8 rows)
+
+--
+-- Run condition optimization tests
+--
+-- row_number with < operator (should use run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 < 3)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- row_number with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- rank with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- dense_rank with = operator (should convert to <= for run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.dr = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (dense_rank() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+ empno | salary | dr
+-------+--------+----
+ 8 | 6000 | 1
+(1 row)
+
+-- count(*) with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+ QUERY PLAN
+---------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary)
+ Run Condition: (count(*) OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+ empno | salary | c
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 3
+ 11 | 5200 | 3
+(3 rows)
+
+--
+-- WHERE pushdown tests
+-- Quals on PARTITION BY columns without window functions can be pushed to WHERE
+--
+-- depname is in PARTITION BY, should be pushed to WHERE (SeqScan filter)
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop';
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'develop'::text)
+(7 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop'
+ORDER BY salary DESC;
+ depname | empno | salary | rnk
+---------+-------+--------+-----
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+(3 rows)
+
+-- Mixed: depname pushed to WHERE, rank condition stays as run condition
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rnk = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'sales'::text)
+(9 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+ depname | empno | salary | rnk
+---------+-------+--------+-----
+ sales | 1 | 5000 | 1
+(1 row)
+
+--
+-- QUALIFY without window function in SELECT list
+-- The window function appears only in QUALIFY
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify4 = 1)
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+ depname | empno | salary
+-----------+-------+--------
+ develop | 8 | 6000
+ personnel | 2 | 3900
+ sales | 1 | 5000
+(3 rows)
+
+-- With PARTITION BY column filter pushed down
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify4 = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'develop'::text)
+(9 rows)
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+ depname | empno | salary
+---------+-------+--------
+ develop | 8 | 6000
+(1 row)
+
+--
+-- Multiple window functions with different windows
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: ((pg_qualify.rn_asc = 1) OR (pg_qualify.rn_desc = 1))
+ -> WindowAgg
+ Window: w2 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Incremental Sort
+ Sort Key: empsalary.depname, empsalary.salary
+ Presorted Key: empsalary.depname
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(12 rows)
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1
+ORDER BY depname, empno;
+ depname | empno | salary | rn_asc | rn_desc
+-----------+-------+--------+--------+---------
+ develop | 7 | 4200 | 1 | 5
+ develop | 8 | 6000 | 5 | 1
+ personnel | 2 | 3900 | 2 | 1
+ personnel | 5 | 3500 | 1 | 2
+ sales | 1 | 5000 | 3 | 1
+ sales | 4 | 4800 | 1 | 2
+(6 rows)
+
+--
+-- QUALIFY with aggregate and window functions
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ -> WindowAgg
+ Window: w1 AS (ORDER BY (sum(empsalary.salary)) ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: (sum(empsalary.salary)) DESC
+ -> HashAggregate
+ Group Key: empsalary.depname
+ -> Seq Scan on empsalary
+(9 rows)
+
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+ depname | total | rnk
+---------+-------+-----
+ develop | 25100 | 1
+ sales | 14600 | 2
+(2 rows)
+
+--
+-- QUALIFY in a grouped query without window functions.
+-- The condition is validated like a SELECT-list item, so aggregates and
+-- grouping columns are allowed (and behave as HAVING would).
+--
+-- Aggregate used directly in QUALIFY filters groups like HAVING
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY count(*) > 2
+ORDER BY depname;
+ depname | c
+---------+---
+ develop | 5
+ sales | 3
+(2 rows)
+
+-- A grouping column may be referenced directly in QUALIFY
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY depname <> 'sales'
+ORDER BY depname;
+ depname | c
+-----------+---
+ develop | 5
+ personnel | 2
+(2 rows)
+
+--
+-- Comparison with equivalent subquery (results should match)
+--
+-- Subquery version
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- QUALIFY version (should produce same results)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+--
+-- QUALIFY with different comparison operators
+--
+-- Greater than (no run condition optimization for increasing functions)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn > 7)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7
+ORDER BY empno;
+ empno | rn
+-------+----
+ 9 | 8
+ 10 | 9
+ 11 | 10
+(3 rows)
+
+-- Equality
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn = 5)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+ empno | rn
+-------+----
+ 5 | 5
+(1 row)
+
+-- BETWEEN (should keep as filter)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn >= 3)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5
+ORDER BY empno;
+ empno | rn
+-------+----
+ 3 | 3
+ 4 | 4
+ 5 | 5
+(3 rows)
+
+-- IN list
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5);
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn = ANY ('{1,3,5}'::bigint[]))
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5)
+ORDER BY empno;
+ empno | rn
+-------+----
+ 1 | 1
+ 3 | 3
+ 5 | 5
+(3 rows)
+
+--
+-- QUALIFY with expressions
+--
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+ empno | salary | rn
+-------+--------+----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 3
+ 1 | 5000 | 4
+ 4 | 4800 | 5
+(5 rows)
+
+--
+-- Error cases
+--
+-- Aggregate in QUALIFY without GROUP BY: just as in the SELECT list, the
+-- non-aggregated output columns make this an error (must appear in GROUP BY).
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY sum(salary) > 5000;
+ERROR: column "empsalary.depname" must appear in the GROUP BY clause or be used in an aggregate function
+LINE 1: SELECT depname, empno, salary
+ ^
+-- QUALIFY in a grouped query referencing an ungrouped column (should error,
+-- just as such a reference would in the SELECT list)
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY salary > 100;
+ERROR: column "empsalary.salary" must appear in the GROUP BY clause or be used in an aggregate function
+LINE 4: QUALIFY salary > 100;
+ ^
+-- QUALIFY with set-returning function (should error)
+SELECT empno, salary
+FROM empsalary
+QUALIFY generate_series(1, 3) > 1;
+ERROR: set-returning functions are not allowed in QUALIFY
+LINE 3: QUALIFY generate_series(1, 3) > 1;
+ ^
+--
+-- QUALIFY in different query structures
+--
+-- With DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------
+ Unique
+ -> Incremental Sort
+ Sort Key: pg_qualify.depname, pg_qualify.top_emp
+ Presorted Key: pg_qualify.depname
+ -> Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify3 = 1)
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(12 rows)
+
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+ depname | top_emp
+-----------+---------
+ develop | 8
+ personnel | 2
+ sales | 1
+(3 rows)
+
+-- With ORDER BY
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | rnk
+-------+--------+-----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- With LIMIT (QUALIFY is evaluated before LIMIT)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+LIMIT 3;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Limit
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+ORDER BY salary DESC
+LIMIT 3;
+ empno | salary | rn
+-------+--------+----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 3
+(3 rows)
+
+--
+-- Verify evaluation order: QUALIFY happens after window functions, before DISTINCT
+--
+-- This should first compute row_number, then filter, then apply DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ HashAggregate
+ Group Key: empsalary.salary, row_number() OVER w1
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+ salary | rn
+--------+----
+ 5200 | 2
+ 5200 | 3
+ 6000 | 1
+(3 rows)
+
+-- QUALIFY with FILTERS over window function
+EXPLAIN(COSTS OFF) SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rank = 1)
+ -> WindowAgg
+ Window: w2 AS (ORDER BY empsalary.depname ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w2 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.depname)
+ -> Sort
+ Sort Key: empsalary.depname DESC
+ -> HashAggregate
+ Group Key: empsalary.depname
+ -> Seq Scan on empsalary
+(14 rows)
+
+SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+ sum | rank | filtered_sum | depname
+-------+------+--------------+---------
+ 25100 | 1 | 22600 | develop
+(1 row)
+
+--
+-- Aggregate functions directly in QUALIFY
+-- (allowed in a grouped query, the same as in the SELECT list / HAVING)
+--
+-- Aggregate condition over the group
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000;
+ QUERY PLAN
+-------------------------------------------------
+ Subquery Scan on pg_qualify
+ -> HashAggregate
+ Group Key: empsalary.depname
+ Filter: (sum(empsalary.salary) > 15000)
+ -> Seq Scan on empsalary
+(5 rows)
+
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000
+ORDER BY depname;
+ depname | total
+---------+-------
+ develop | 25100
+(1 row)
+
+-- Aggregate and window function combined in QUALIFY
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY rank() OVER (ORDER BY sum(salary) DESC) = 1
+ORDER BY depname;
+ depname | total
+---------+-------
+ develop | 25100
+(1 row)
+
+-- Whole-table aggregate (single group)
+SELECT sum(salary) AS s
+FROM empsalary
+QUALIFY sum(salary) > 1000;
+ s
+-------
+ 47100
+(1 row)
+
+--
+-- Name resolution tests
+--
+-- An input column takes precedence over a same-named select-list alias
+-- "salary" in QUALIFY is the input column (> 4000 keeps most rows), not the
+-- alias (which is 0 and would keep none)
+SELECT empno, (empno * 0) AS salary
+FROM empsalary
+QUALIFY salary > 4000
+ORDER BY empno;
+ empno | salary
+-------+--------
+ 1 | 0
+ 3 | 0
+ 4 | 0
+ 7 | 0
+ 8 | 0
+ 9 | 0
+ 10 | 0
+ 11 | 0
+(8 rows)
+
+-- QUALIFY referecing columns that not on output result
+-- Same column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY salary;
+ depname
+-----------
+ personnel
+ personnel
+ develop
+ develop
+ sales
+ sales
+ sales
+ develop
+ develop
+ develop
+(10 rows)
+
+-- Different column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY enroll_date;
+ depname
+-----------
+ sales
+ develop
+ personnel
+ sales
+ develop
+ sales
+ develop
+ personnel
+ develop
+ develop
+(10 rows)
+
+--
+-- Name resolution error cases
+--
+-- A non-deterministic alias expression cannot be referenced from QUALIFY
+SELECT empno, (random() < 2)::int AS r
+FROM empsalary
+QUALIFY r = 1;
+ERROR: QUALIFY cannot reference output column "r" whose expression is non-deterministic
+LINE 3: QUALIFY r = 1;
+ ^
+-- An ambiguous alias reference is rejected
+SELECT empno AS x, salary AS x,
+ row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY x > 0;
+ERROR: column reference "x" is ambiguous
+LINE 4: QUALIFY x > 0;
+ ^
+-- A name that is neither an input column nor a select-list alias
+SELECT empno
+FROM empsalary
+QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+ERROR: column "nosuchcol" does not exist
+LINE 3: QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+ ^
+--
+-- QUALIFY without any window function: a general post-SELECT filter
+--
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000;
+ QUERY PLAN
+----------------------------------
+ Seq Scan on empsalary
+ Filter: ((salary * 2) > 10000)
+(2 rows)
+
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000
+ORDER BY empno;
+ empno | salary | new_salary
+-------+--------+------------
+ 8 | 6000 | 12000
+ 10 | 5200 | 10400
+ 11 | 5200 | 10400
+(3 rows)
+
+--
+-- QUALIFY in other query structures
+--
+-- In the arms of a set operation
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary) = 1
+UNION ALL
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary DESC) = 1
+ORDER BY empno;
+ empno
+-------
+ 5
+ 8
+(2 rows)
+
+-- In a subquery that carries an outer reference
+SELECT depname,
+ (SELECT empno FROM empsalary e2
+ WHERE e2.depname = e1.depname
+ QUALIFY row_number() OVER (ORDER BY salary DESC) = 1) AS top_emp
+FROM (SELECT DISTINCT depname FROM empsalary) e1
+ORDER BY depname;
+ depname | top_emp
+-----------+---------
+ develop | 8
+ personnel | 2
+ sales | 1
+(3 rows)
+
+-- Combined with row-level locking (the lock applies to the base table)
+SELECT empno FROM empsalary
+QUALIFY salary > 5000
+ORDER BY empno
+FOR UPDATE;
+ empno
+-------
+ 8
+ 10
+ 11
+(3 rows)
+
+--
+-- Cleanup
+--
+DROP TABLE empsalary;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 8fa0a6c47fb..278554a7307 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -102,7 +102,7 @@ test: publication subscription
# Another group of parallel tests
# select_views depends on create_view
# ----------
-test: select_views portals_p2 foreign_key dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite graph_table
+test: select_views portals_p2 foreign_key dependency guc bitmapops combocid tsearch tsdicts foreign_data window qualify xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite graph_table
# ----------
# Another group of parallel tests (JSON related)
diff --git a/src/test/regress/sql/qualify.sql b/src/test/regress/sql/qualify.sql
new file mode 100644
index 00000000000..c9bf99e23fe
--- /dev/null
+++ b/src/test/regress/sql/qualify.sql
@@ -0,0 +1,563 @@
+--
+-- QUALIFY clause tests
+--
+
+CREATE TEMPORARY TABLE empsalary (
+ depname varchar,
+ empno bigint,
+ salary int,
+ enroll_date date
+);
+
+INSERT INTO empsalary VALUES
+('develop', 10, 5200, '2007-08-01'),
+('sales', 1, 5000, '2006-10-01'),
+('personnel', 5, 3500, '2007-12-10'),
+('sales', 4, 4800, '2007-08-08'),
+('personnel', 2, 3900, '2006-12-23'),
+('develop', 7, 4200, '2008-01-01'),
+('develop', 9, 4500, '2008-01-01'),
+('sales', 3, 4800, '2007-08-01'),
+('develop', 8, 6000, '2006-10-01'),
+('develop', 11, 5200, '2007-08-15');
+
+--
+-- Basic QUALIFY functionality
+--
+
+-- Simple QUALIFY with inline window function
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC, empno;
+
+-- QUALIFY with named window
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2
+ORDER BY depname, salary DESC, empno;
+
+--
+-- Alias resolution tests
+--
+
+-- Reference alias defined in SELECT
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2
+ORDER BY depname, salary DESC, empno;
+
+-- Reference alias with row_number
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+-- Multiple aliases
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2;
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2
+ORDER BY depname, salary DESC;
+
+--
+-- Run condition optimization tests
+--
+
+-- row_number with < operator (should use run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+-- row_number with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+
+-- rank with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+-- dense_rank with = operator (should convert to <= for run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+
+-- count(*) with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+
+--
+-- WHERE pushdown tests
+-- Quals on PARTITION BY columns without window functions can be pushed to WHERE
+--
+
+-- depname is in PARTITION BY, should be pushed to WHERE (SeqScan filter)
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop';
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop'
+ORDER BY salary DESC;
+
+-- Mixed: depname pushed to WHERE, rank condition stays as run condition
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+
+--
+-- QUALIFY without window function in SELECT list
+-- The window function appears only in QUALIFY
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+
+-- With PARTITION BY column filter pushed down
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+
+--
+-- Multiple window functions with different windows
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1;
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1
+ORDER BY depname, empno;
+
+--
+-- QUALIFY with aggregate and window functions
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+
+--
+-- QUALIFY in a grouped query without window functions.
+-- The condition is validated like a SELECT-list item, so aggregates and
+-- grouping columns are allowed (and behave as HAVING would).
+--
+
+-- Aggregate used directly in QUALIFY filters groups like HAVING
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY count(*) > 2
+ORDER BY depname;
+
+-- A grouping column may be referenced directly in QUALIFY
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY depname <> 'sales'
+ORDER BY depname;
+
+--
+-- Comparison with equivalent subquery (results should match)
+--
+
+-- Subquery version
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3;
+
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3
+ORDER BY salary DESC, empno;
+
+-- QUALIFY version (should produce same results)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3
+ORDER BY salary DESC, empno;
+
+--
+-- QUALIFY with different comparison operators
+--
+
+-- Greater than (no run condition optimization for increasing functions)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7
+ORDER BY empno;
+
+-- Equality
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+
+-- BETWEEN (should keep as filter)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5
+ORDER BY empno;
+
+-- IN list
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5);
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5)
+ORDER BY empno;
+
+--
+-- QUALIFY with expressions
+--
+
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+
+--
+-- Error cases
+--
+
+-- Aggregate in QUALIFY without GROUP BY: just as in the SELECT list, the
+-- non-aggregated output columns make this an error (must appear in GROUP BY).
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY sum(salary) > 5000;
+
+-- QUALIFY in a grouped query referencing an ungrouped column (should error,
+-- just as such a reference would in the SELECT list)
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY salary > 100;
+
+-- QUALIFY with set-returning function (should error)
+SELECT empno, salary
+FROM empsalary
+QUALIFY generate_series(1, 3) > 1;
+
+--
+-- QUALIFY in different query structures
+--
+
+-- With DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+
+-- With ORDER BY
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3;
+
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3
+ORDER BY salary DESC, empno;
+
+-- With LIMIT (QUALIFY is evaluated before LIMIT)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+LIMIT 3;
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+ORDER BY salary DESC
+LIMIT 3;
+
+--
+-- Verify evaluation order: QUALIFY happens after window functions, before DISTINCT
+--
+
+-- This should first compute row_number, then filter, then apply DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+
+-- QUALIFY with FILTERS over window function
+EXPLAIN(COSTS OFF) SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+
+SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+
+--
+-- Aggregate functions directly in QUALIFY
+-- (allowed in a grouped query, the same as in the SELECT list / HAVING)
+--
+
+-- Aggregate condition over the group
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000;
+
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000
+ORDER BY depname;
+
+-- Aggregate and window function combined in QUALIFY
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY rank() OVER (ORDER BY sum(salary) DESC) = 1
+ORDER BY depname;
+
+-- Whole-table aggregate (single group)
+SELECT sum(salary) AS s
+FROM empsalary
+QUALIFY sum(salary) > 1000;
+
+--
+-- Name resolution tests
+--
+
+-- An input column takes precedence over a same-named select-list alias
+-- "salary" in QUALIFY is the input column (> 4000 keeps most rows), not the
+-- alias (which is 0 and would keep none)
+SELECT empno, (empno * 0) AS salary
+FROM empsalary
+QUALIFY salary > 4000
+ORDER BY empno;
+
+-- QUALIFY referecing columns that not on output result
+
+-- Same column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY salary;
+
+-- Different column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY enroll_date;
+
+--
+-- Name resolution error cases
+--
+
+-- A non-deterministic alias expression cannot be referenced from QUALIFY
+SELECT empno, (random() < 2)::int AS r
+FROM empsalary
+QUALIFY r = 1;
+
+-- An ambiguous alias reference is rejected
+SELECT empno AS x, salary AS x,
+ row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY x > 0;
+
+-- A name that is neither an input column nor a select-list alias
+SELECT empno
+FROM empsalary
+QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+
+--
+-- QUALIFY without any window function: a general post-SELECT filter
+--
+
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000;
+
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000
+ORDER BY empno;
+
+--
+-- QUALIFY in other query structures
+--
+
+-- In the arms of a set operation
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary) = 1
+UNION ALL
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary DESC) = 1
+ORDER BY empno;
+
+-- In a subquery that carries an outer reference
+SELECT depname,
+ (SELECT empno FROM empsalary e2
+ WHERE e2.depname = e1.depname
+ QUALIFY row_number() OVER (ORDER BY salary DESC) = 1) AS top_emp
+FROM (SELECT DISTINCT depname FROM empsalary) e1
+ORDER BY depname;
+
+-- Combined with row-level locking (the lock applies to the base table)
+SELECT empno FROM empsalary
+QUALIFY salary > 5000
+ORDER BY empno
+FOR UPDATE;
+
+--
+-- Cleanup
+--
+DROP TABLE empsalary;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 56c1f997f88..3eaceb8a593 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2500,6 +2500,9 @@ QTNode
QUERYTYPE
QualCost
QualItem
+QualifyExtractContext
+QualifyHookState
+QualifyVarmapContext
Query
QueryCompletion
QueryDesc
--
2.50.1 (Apple Git-155)
v3-0001-Add-QUALIFY-clause.patch.nocfbot (text/plain, 86.3K) download
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 11:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Re: Proposal: QUALIFY clause Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-29 00:46 ` Re: Proposal: QUALIFY clause David Rowley <dgrowleyml@gmail.com>
2025-07-29 09:48 ` Re: Proposal: QUALIFY clause Richard Guo <guofenglinux@gmail.com>
2026-06-29 14:41 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2026-07-14 18:23 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2026-09-24 13:06 ` Matheus Alcantara <matheusssilv97@gmail.com>
0 siblings, 0 replies; 41+ messages in thread
From: Matheus Alcantara @ 2026-09-24 13:06 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Vik Fearing <vik@postgresfriends.org>; Marcos Pegoraro <marcos@f10.com.br>; Peter Eisentraut <peter@eisentraut.org>; Richard Guo <guofenglinux@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>
On 14/07/26 15:23, Matheus Alcantara wrote:
>
> [ ... ]
>
>> So there are two patches attached:
>>
>> - v2-0001-Add-QUALIFY-clause.patch: the query-rewrite approach, complete (window and
>> non-window QUALIFY), with docs and tests.
>>
>> - v2-0001-Add-QUALIFY-clause.patch.nocfbot: the planner-based approach,
>> window-functions only. Note that there is some test cases failing due
>> to WIP state.
>>
>
> CFBot was not happy with v2 due to some compiler warnings. Attaching v3
> with fixes, not major changes compared with v2.
>
v3 needs a rebase. Attaching v4 rebased, no changes compared with v3.
--
Matheus Alcantara
EDB: https://www.enterprisedb.com
Attachments:
v4-0001-Add-QUALIFY-clause.patch (text/plain, 85.7K) download
From d7c4877793f8426c3503f82918b6f475af2ce876 Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <mths.dev@pm.me>
Date: Mon, 29 Jun 2026 10:49:43 -0300
Subject: [PATCH v4] Add QUALIFY clause
QUALIFY filters rows using the result of a window function without
requiring the query to be wrapped in a subquery or CTE. It is to window
functions what HAVING is to aggregates: a post-SELECT filter, evaluated
after the window functions have been computed but before DISTINCT, ORDER
BY, and LIMIT. The condition may contain window functions directly,
whether or not they also appear in the select list, and it may reference
select-list output names, which are not visible to WHERE or HAVING.
The clause is implemented in the parser by rewriting a query
specification that carries a QUALIFY clause into an equivalent two-level
query: an inner subquery holding the table expression and select list,
wrapped by an outer query whose WHERE clause is the QUALIFY condition.
This follows the syntactic transformation described in the SQL standard
change proposal. Because the planner already optimizes window functions
that appear inside a subquery, the rewritten form obtains window run
conditions and quals pushdown without any new planner code, producing
plans identical to those of the equivalent hand-written subquery.
The condition is transformed in the scope of the inner query, so a name
that refers to a column of the FROM tables resolves to that column in
preference to a select-list alias of the same name. Window functions,
aggregates, and inner columns referenced by the condition are projected
through the subquery and referenced from the outer WHERE clause by Vars
nodes, which preserves the comparison shape that the run-condition
machinery recognizes. Because QUALIFY is evaluated after the select
list, the ORDER BY, DISTINCT, and LIMIT clauses are processed against
the outer query.
QUALIFY is added as a reserved keyword, as required by the standard.
---
doc/src/sgml/ref/select.sgml | 99 +++
src/backend/nodes/nodeFuncs.c | 2 +
src/backend/parser/analyze.c | 504 +++++++++++
src/backend/parser/gram.y | 16 +-
src/backend/parser/parse_agg.c | 4 +
src/backend/parser/parse_expr.c | 4 +
src/backend/parser/parse_func.c | 3 +
src/include/nodes/parsenodes.h | 1 +
src/include/parser/kwlist.h | 1 +
src/include/parser/parse_node.h | 1 +
src/test/regress/expected/qualify.out | 1122 +++++++++++++++++++++++++
src/test/regress/parallel_schedule | 2 +-
src/test/regress/sql/qualify.sql | 563 +++++++++++++
src/tools/pgindent/typedefs.list | 3 +
14 files changed, 2320 insertions(+), 5 deletions(-)
create mode 100644 src/test/regress/expected/qualify.out
create mode 100644 src/test/regress/sql/qualify.sql
diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml
index 18392f7caec..e61d3826a0e 100644
--- a/doc/src/sgml/ref/select.sgml
+++ b/doc/src/sgml/ref/select.sgml
@@ -40,6 +40,7 @@ SELECT [ ALL | DISTINCT [ ON ( <replaceable class="parameter">expression</replac
[ GROUP BY [ ALL | DISTINCT ] <replaceable class="parameter">grouping_element</replaceable> [, ...] ]
[ HAVING <replaceable class="parameter">condition</replaceable> ]
[ WINDOW <replaceable class="parameter">window_name</replaceable> AS ( <replaceable class="parameter">window_definition</replaceable> ) [, ...] ]
+ [ QUALIFY <replaceable class="parameter">condition</replaceable> ]
[ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <replaceable class="parameter">select</replaceable> ]
[ ORDER BY <replaceable class="parameter">expression</replaceable> [ ASC | DESC | USING <replaceable class="parameter">operator</replaceable> ] [ NULLS { FIRST | LAST } ] [, ...] ]
[ LIMIT { <replaceable class="parameter">count</replaceable> | ALL } ]
@@ -145,6 +146,16 @@ TABLE [ ONLY ] <replaceable class="parameter">table_name</replaceable> [ * ]
</para>
</listitem>
+ <listitem>
+ <para>
+ If the <literal>QUALIFY</literal> clause is specified, all rows
+ that do not satisfy the condition are eliminated from the output.
+ Because <literal>QUALIFY</literal> is applied after the output rows
+ have been computed, its condition can reference window functions
+ and output column names. (See <xref linkend="sql-qualify"/> below.)
+ </para>
+ </listitem>
+
<listitem>
<para><literal>SELECT DISTINCT</literal> eliminates duplicate rows from the
result. <literal>SELECT DISTINCT ON</literal> eliminates rows that
@@ -1191,6 +1202,83 @@ EXCLUDE NO OTHERS
</note>
</refsect2>
+ <refsect2 id="sql-qualify" xreflabel="QUALIFY Clause">
+ <title><literal>QUALIFY</literal> Clause</title>
+
+ <para>
+ The optional <literal>QUALIFY</literal> clause has the general form
+<synopsis>
+QUALIFY <replaceable class="parameter">condition</replaceable>
+</synopsis>
+ where <replaceable class="parameter">condition</replaceable> is
+ any expression that evaluates to a result of type
+ <type>boolean</type>, the same as specified for the
+ <literal>WHERE</literal> clause.
+ </para>
+
+ <para>
+ <literal>QUALIFY</literal> eliminates rows that do not satisfy the
+ condition. It is applied after window functions have been computed,
+ so its condition may refer to the results of window functions. In
+ this respect <literal>QUALIFY</literal> is to window functions what
+ <link linkend="sql-having"><literal>HAVING</literal></link> is to
+ aggregate functions: each filters the result of its corresponding
+ computation stage. Without <literal>QUALIFY</literal>, filtering on
+ the result of a window function requires wrapping the query in a
+ sub-query (or common table expression) and applying a
+ <literal>WHERE</literal> clause there, because window functions are
+ computed after <literal>WHERE</literal> and <literal>HAVING</literal>.
+ A row is retained only if the condition evaluates to true; rows for
+ which it evaluates to false or null are eliminated.
+ </para>
+
+ <para>
+ The condition may contain window functions, whether or not the same
+ window functions also appear in the <command>SELECT</command> list.
+ These window functions may use an inline <literal>OVER</literal>
+ clause or refer to a window defined in the
+ <link linkend="sql-window"><literal>WINDOW</literal></link> clause; a
+ <literal>WINDOW</literal> clause is not required. Because
+ <literal>QUALIFY</literal> is evaluated after the
+ <command>SELECT</command> list, the condition may also reference
+ output column names (column aliases defined in the
+ <command>SELECT</command> list), unlike <literal>WHERE</literal> and
+ <literal>HAVING</literal>. In case of ambiguity, a name in
+ <literal>QUALIFY</literal> is interpreted as an input-column name
+ rather than an output column name.
+ </para>
+
+ <para>
+ <literal>QUALIFY</literal> does not require window functions to be
+ present; it is a general filter applied to the computed output rows.
+ A condition that does not involve a window function and refers only to
+ input columns produces the same result as if it had been written in
+ <literal>WHERE</literal>, though writing such conditions in
+ <literal>WHERE</literal> is preferred. Aggregate functions are
+ permitted in the condition under the same rules that apply to the
+ <command>SELECT</command> list, since aggregation has already occurred
+ by the time <literal>QUALIFY</literal> is evaluated.
+ </para>
+
+ <para>
+ The following query returns, for each department, only the
+ highest-paid employees, filtering on the result of a window function
+ without a sub-query:
+<programlisting>
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS pos
+FROM empsalary
+QUALIFY pos = 1;
+</programlisting>
+ Here the output column name <literal>pos</literal> defined in the
+ <command>SELECT</command> list is referenced in
+ <literal>QUALIFY</literal>. The window function could equally be
+ spelled out in the <literal>QUALIFY</literal> condition itself, in
+ which case it need not appear in the <command>SELECT</command> list at
+ all.
+ </para>
+ </refsect2>
+
<refsect2 id="sql-distinct" xreflabel="DISTINCT Clause">
<title><literal>DISTINCT</literal> Clause</title>
@@ -1994,6 +2082,17 @@ FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
missing features.
</para>
+ <refsect2>
+ <title>The <literal>QUALIFY</literal> Clause</title>
+
+ <para>
+ The <literal>QUALIFY</literal> clause conforms to the SQL standard
+ (feature O001, <quote>QUALIFY clause</quote>). Note that
+ <literal>QUALIFY</literal> is a reserved word; existing applications
+ that use it as an identifier must quote it or choose another name.
+ </para>
+ </refsect2>
+
<refsect2>
<title>Omitted <literal>FROM</literal> Clauses</title>
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 9512a6a824a..b20682c4f7c 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -4383,6 +4383,8 @@ raw_expression_tree_walker_impl(Node *node,
return true;
if (WALK(stmt->rarg))
return true;
+ if (WALK(stmt->qualifyClause))
+ return true;
}
break;
case T_PLAssignStmt:
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 08f99dff711..6b5fb116264 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -49,6 +49,7 @@
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
+#include "rewrite/rewriteManip.h"
#include "utils/backend_status.h"
#include "utils/builtins.h"
#include "utils/guc.h"
@@ -64,6 +65,31 @@ typedef struct SelectStmtPassthrough
List *indirection; /* indirection yet to be applied to target */
} SelectStmtPassthrough;
+/* State for the QUALIFY select-list alias resolution hook */
+typedef struct QualifyHookState
+{
+ List *targetList; /* target list to match aliases against */
+ PostParseColumnRefHook prev_hook; /* previously installed hook, if any */
+ void *prev_hook_state; /* its state */
+} QualifyHookState;
+
+/* Working state for qualifyExtractMutator */
+typedef struct QualifyExtractContext
+{
+ List **innerTargetList; /* inner query's target list (appended to) */
+ int subquery_varno; /* varno of the subquery RTE in the outer
+ * query */
+ int next_resno; /* next resno to assign to appended entries */
+} QualifyExtractContext;
+
+/* Working state for qualifyFixupVarattno */
+typedef struct QualifyVarmapContext
+{
+ int subquery_varno; /* varno whose Vars are to be remapped */
+ AttrNumber *attmap; /* map from old resno to new resno */
+} QualifyVarmapContext;
+
+
/* Hook for plugins to get control at end of parse analysis */
post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
@@ -100,6 +126,10 @@ static Query *transformCallStmt(ParseState *pstate,
CallStmt *stmt);
static void transformLockingClause(ParseState *pstate, Query *qry,
LockingClause *lc, bool pushedDown);
+static Node *qualifyPostColumnRefHook(ParseState *pstate, ColumnRef *cref,
+ Node *var);
+static Query *rewriteQualifyQuery(ParseState *pstate, Query *innerQuery,
+ Node *qualifyExpr);
#ifdef DEBUG_NODE_TESTS_ENABLED
static bool test_raw_expression_coverage(Node *node, void *context);
#endif
@@ -1402,6 +1432,427 @@ count_rowexpr_columns(ParseState *pstate, Node *expr)
return -1;
}
+/*
+ * qualifyPostColumnRefHook
+ * Resolve a QUALIFY column references
+ *
+ * QUALIFY column references can reference table columns and target alias. A
+ * real column of the FROM tables take precedence over a select-list alias of
+ * the same name.
+ */
+static Node *
+qualifyPostColumnRefHook(ParseState *pstate, ColumnRef *cref, Node *var)
+{
+ QualifyHookState *qstate = (QualifyHookState *) pstate->p_ref_hook_state;
+ char *name;
+ TargetEntry *matched = NULL;
+ ListCell *lc;
+
+ /* A real column of the FROM tables takes precedence over an alias. */
+ if (var != NULL)
+ return NULL;
+
+ /* Only unqualified (single-field) names can match a select-list alias. */
+ if (list_length(cref->fields) != 1 || !IsA(linitial(cref->fields), String))
+ return NULL;
+
+ name = strVal(linitial(cref->fields));
+
+ foreach(lc, qstate->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resjunk || tle->resname == NULL || strcmp(tle->resname, name) != 0)
+ continue;
+
+ if (matched != NULL && !equal(matched->expr, tle->expr))
+ ereport(ERROR,
+ (errcode(ERRCODE_AMBIGUOUS_COLUMN),
+ errmsg("column reference \"%s\" is ambiguous", name),
+ parser_errposition(pstate, cref->location)));
+ matched = tle;
+ }
+
+ if (matched == NULL)
+ return NULL;
+
+ /*
+ * XXX: an alias whose expression is non-deterministic would be evaluated
+ * once for the select-list column and again in the outer filter built
+ * from the QUALIFY condition, possibly producing different values. Until
+ * such references are resolved by the identity of the select-list entry
+ * (projecting it once and referencing it by a single Var), reject
+ * volatile alias expressions.
+ */
+ if (contain_volatile_functions((Node *) matched->expr))
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("QUALIFY cannot reference output column \"%s\" whose expression is non-deterministic",
+ name),
+ parser_errposition(pstate, cref->location)));
+
+ return copyObject((Node*) matched->expr);
+}
+
+/*
+ * qualifyExtractMutator
+ * Rewrite a QUALIFY condition so it can serve as the WHERE clause of the
+ * outer query built by rewriteQualifyQuery.
+ *
+ * Every window function, aggregate, and Var of the inner query is computed by
+ * the inner query and referenced from the outer query by a plain Var: we find
+ * an existing target entry with an equal expression, or append a new resjunk
+ * one, and replace the node with an outer Var. Comparisons and other
+ * operators are left in place at the outer level. This reproduces the shape
+ * of a hand-written subquery, so the planner's existing optimizations for
+ * window functions in subqueries (run conditions and qual pushdown) apply
+ * unchanged.
+ */
+static Node *
+qualifyExtractMutator(Node *node, QualifyExtractContext *ctx)
+{
+ if (node == NULL)
+ return NULL;
+
+ if (IsA(node, WindowFunc) || IsA(node, Aggref)
+ || (IsA(node, Var) && ((Var *) node)->varlevelsup == 0))
+ {
+ TargetEntry *tle = NULL;
+
+ /* Reuse a matching target entry so a value isn't projected twice. */
+ foreach_ptr(TargetEntry, cur, *ctx->innerTargetList)
+ {
+ if (equal(cur->expr, node))
+ {
+ tle = cur;
+ break;
+ }
+ }
+
+ /*
+ * Did not find the target entry on target list so add it on inner
+ * query target list so it can be referenced on the outer query.
+ */
+ if (tle == NULL)
+ {
+ tle = makeTargetEntry((Expr *) copyObject(node),
+ ctx->next_resno++,
+ NULL,
+ false);
+ *ctx->innerTargetList = lappend(*ctx->innerTargetList, tle);
+ }
+
+ /*
+ * The entry is referenced from the outer query, so it must be a real
+ * (non-resjunk) output column of the subquery. A reused entry might
+ * be a resjunk grouping column or a junk ORDER BY/DISTINCT target, so
+ * clear the flag here.
+ */
+ tle->resjunk = false;
+
+ return (Node *) makeVarFromTargetEntry(ctx->subquery_varno, tle);
+ }
+
+ return expression_tree_mutator(node, qualifyExtractMutator, ctx);
+}
+
+/*
+ * qualifyFixupVarattno
+ * Remap the attribute numbers of Vars referencing the QUALIFY subquery,
+ * after the subquery's target list has been renumbered.
+ */
+static bool
+qualifyFixupVarattno(Node *node, QualifyVarmapContext *ctx)
+{
+ if (node == NULL)
+ return false;
+
+ if (IsA(node, Var))
+ {
+ Var *var = (Var *) node;
+
+ if (var->varlevelsup == 0 && var->varno == ctx->subquery_varno)
+ {
+ var->varattno = ctx->attmap[var->varattno];
+ var->varattnosyn = var->varattno;
+ }
+ return false;
+ }
+
+ return expression_tree_walker(node, qualifyFixupVarattno, ctx);
+}
+
+/*
+ * rewriteQualifyQuery
+ * Implement the QUALIFY clause by rewriting the inner query in an outer
+ * query whose WHERE clause is the QUALIFY condition.
+ *
+ * 'innerQuery' is the fully-analyzed query for the table expression and select
+ * list, with the resolved QUALIFY condition appended to its target list as a
+ * resjunk entry. We remove that entry, decompose the condition into the outer
+ * WHERE clause (extracting window functions, aggregates, and inner Vars into
+ * the inner target list), and process the deferred ORDER BY, DISTINCT, and
+ * LIMIT clauses against the outer query.
+ */
+static Query *
+rewriteQualifyQuery(ParseState *pstate, Query *innerQuery, Node *qualifyExpr)
+{
+ Query *outerQuery = makeNode(Query);
+ List *outerTargetList = NIL;
+ List *origTargetList = NIL;
+ List *nonjunk = NIL;
+ List *junk = NIL;
+ Bitmapset *liftrefs = NULL;
+ ParseState *opstate;
+ ParseNamespaceItem *nsitem;
+ QualifyExtractContext ctx;
+ Node *outerQual;
+ List *outerSortClause;
+ List *outerDistinctClause;
+ bool outerHasDistinctOn;
+ Node *outerLimitOffset;
+ Node *outerLimitCount;
+ LimitOption outerLimitOption;
+ ListCell *lc;
+ int resno;
+ int ntargets;
+ AttrNumber *attmap;
+ QualifyVarmapContext mapctx;
+ AttrNumber newresno;
+
+ /*
+ * ORDER BY, DISTINCT, and LIMIT were transformed against the inner
+ * query's scope but are logically evaluated after QUALIFY, so they move
+ * to the outer query. Detach them from the inner query; the sort and
+ * distinct clauses are re-attached below after the columns they reference
+ * are exposed as subquery outputs.
+ */
+ outerSortClause = innerQuery->sortClause;
+ outerDistinctClause = innerQuery->distinctClause;
+ outerHasDistinctOn = innerQuery->hasDistinctOn;
+ outerLimitOffset = innerQuery->limitOffset;
+ outerLimitCount = innerQuery->limitCount;
+ outerLimitOption = innerQuery->limitOption;
+ innerQuery->sortClause = NIL;
+ innerQuery->distinctClause = NIL;
+ innerQuery->hasDistinctOn = false;
+ innerQuery->limitOffset = NULL;
+ innerQuery->limitCount = NULL;
+ innerQuery->limitOption = LIMIT_OPTION_COUNT;
+
+ /* Collect the sort/group refs that the lifted ORDER BY / DISTINCT use. */
+ foreach(lc, outerSortClause)
+ liftrefs = bms_add_member(liftrefs,
+ ((SortGroupClause *) lfirst(lc))->tleSortGroupRef);
+ foreach(lc, outerDistinctClause)
+ liftrefs = bms_add_member(liftrefs,
+ ((SortGroupClause *) lfirst(lc))->tleSortGroupRef);
+
+ /*
+ * Remove the temporary resjunk QUALIFY entry from the inner target list
+ * required by parseCheckAggregates.
+ */
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->expr == (Expr *) qualifyExpr)
+ {
+ Assert(tle->resjunk);
+ innerQuery->targetList = foreach_delete_current(innerQuery->targetList, lc);
+ break;
+ }
+ }
+
+ /*
+ * Capture the original select-list output columns now, before extraction
+ * and lifting may append further (non-resjunk) columns or un-junk
+ * grouping/sort columns; these are what the outer query projects.
+ */
+ foreach_ptr(TargetEntry, tle, innerQuery->targetList)
+ {
+ if (!tle->resjunk)
+ origTargetList = lappend(origTargetList, tle);
+ }
+
+ /*
+ * Extract the QUALIFY condition into the outer WHERE clause, projecting
+ * the inner-query expressions it needs through the subquery. The subquery
+ * will be range-table entry 1 of the outer query.
+ */
+ ctx.innerTargetList = &innerQuery->targetList;
+ ctx.subquery_varno = 1;
+ ctx.next_resno = list_length(innerQuery->targetList) + 1;
+ outerQual = qualifyExtractMutator(qualifyExpr, &ctx);
+
+ /*
+ * Expose as non-resjunk subquery outputs, the inner columns that the
+ * lifted ORDER BY / DISTINCT clauses reference, so the outer query can
+ * refer to them. Grouping columns not referenced by ORDER BY/DISTINCT
+ * stay resjunk.
+ */
+ foreach_ptr(TargetEntry, tle, innerQuery->targetList)
+ {
+ if (tle->ressortgroupref != 0 && bms_is_member(tle->ressortgroupref, liftrefs))
+ tle->resjunk = false;
+ }
+
+ /*
+ * A subquery range table entry requires its non-resjunk columns to come
+ * first with contiguous resnos, and every output column must have a name.
+ * Reorder the inner target list accordingly, name any anonymous output
+ * columns, and remap the resnos referenced by the outer WHERE clause.
+ */
+ ntargets = list_length(innerQuery->targetList);
+ attmap = (AttrNumber *) palloc0((ntargets + 1) * sizeof(AttrNumber));
+
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resjunk)
+ junk = lappend(junk, tle);
+ else
+ nonjunk = lappend(nonjunk, tle);
+ }
+ innerQuery->targetList = list_concat(nonjunk, junk);
+
+ newresno = 1;
+ foreach(lc, innerQuery->targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ attmap[tle->resno] = newresno;
+ tle->resno = newresno;
+
+ /*
+ * Output columns created by extraction are anonymous. Give a Var the
+ * name of its source column, so the lifted ORDER BY/DISTINCT and the
+ * outer WHERE can reference an input column (e.g. "QUALIFY x > 0
+ * ORDER BY x"); fall back to a generated name for non-Var
+ * expressions.
+ */
+ if (!tle->resjunk && tle->resname == NULL)
+ {
+ if (IsA(tle->expr, Var) && ((Var *) tle->expr)->varattno > 0)
+ {
+ Var *var = (Var *) tle->expr;
+
+ tle->resname = get_rte_attribute_name(rt_fetch(var->varno,
+ innerQuery->rtable),
+ var->varattno);
+ }
+ if (tle->resname == NULL)
+ tle->resname = psprintf("qualify%d", newresno);
+ }
+ newresno++;
+ }
+
+ /* Now fix the QUALIFY Var references */
+ mapctx.subquery_varno = ctx.subquery_varno;
+ mapctx.attmap = attmap;
+ qualifyFixupVarattno(outerQual, &mapctx);
+
+ /*
+ * The inner query is now one level deeper than it was, so bump the level
+ * of any outer references it contains. The outer WHERE clause (and the
+ * lifted clauses) stay at the current level.
+ */
+ IncrementVarSublevelsUp((Node *) innerQuery, 1, 1);
+
+ /* Build the outer query's parse state, sharing the original parent. */
+ opstate = make_parsestate(pstate->parentParseState);
+ opstate->p_sourcetext = pstate->p_sourcetext;
+ opstate->p_pre_columnref_hook = pstate->p_pre_columnref_hook;
+ opstate->p_post_columnref_hook = pstate->p_post_columnref_hook;
+ opstate->p_paramref_hook = pstate->p_paramref_hook;
+ opstate->p_coerce_param_hook = pstate->p_coerce_param_hook;
+ opstate->p_ref_hook_state = pstate->p_ref_hook_state;
+
+ outerQuery->commandType = CMD_SELECT;
+
+ nsitem = addRangeTableEntryForSubquery(opstate, innerQuery,
+ makeAlias("pg_qualify", NIL),
+ false, true);
+ addNSItemToQuery(opstate, nsitem, true, true, true);
+
+ /* Outer target list: project the original select-list output columns. */
+ resno = 1;
+ foreach(lc, origTargetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+ Var *var = makeVarFromTargetEntry(ctx.subquery_varno, tle);
+
+ outerTargetList = lappend(outerTargetList,
+ makeTargetEntry((Expr *) var,
+ resno++,
+ tle->resname ? pstrdup(tle->resname) : NULL,
+ false));
+ }
+
+ /*
+ * Re-attach the lifted ORDER BY / DISTINCT clauses. For each inner
+ * column they reference, give the outer target that projects it the same
+ * sort/ group ref so the moved SortGroupClauses line up; a referenced
+ * column not in the projection gets a resjunk outer target.
+ */
+ foreach_ptr(TargetEntry, innerTle, innerQuery->targetList)
+ {
+ TargetEntry *out = NULL;
+
+ if (innerTle->ressortgroupref == 0 || !bms_is_member(innerTle->ressortgroupref, liftrefs))
+ continue;
+
+ foreach_ptr(TargetEntry, outerTle, outerTargetList)
+ {
+
+ if (IsA(outerTle->expr, Var) && ((Var *) outerTle->expr)->varattno == innerTle->resno)
+ {
+ out = outerTle;
+ break;
+ }
+ }
+
+ if (out == NULL)
+ {
+ Var *var = makeVarFromTargetEntry(ctx.subquery_varno, innerTle);
+
+ out = makeTargetEntry((Expr *) var,
+ resno++,
+ innerTle->resname ? pstrdup(innerTle->resname) : NULL,
+ true);
+ outerTargetList = lappend(outerTargetList, out);
+ }
+ out->ressortgroupref = innerTle->ressortgroupref;
+ }
+
+ outerQuery->targetList = outerTargetList;
+ outerQuery->rtable = opstate->p_rtable;
+ outerQuery->rteperminfos = opstate->p_rteperminfos;
+ outerQuery->jointree = makeFromExpr(opstate->p_joinlist, outerQual);
+
+ outerQuery->sortClause = outerSortClause;
+ outerQuery->distinctClause = outerDistinctClause;
+ outerQuery->hasDistinctOn = outerHasDistinctOn;
+ outerQuery->limitOffset = outerLimitOffset;
+ outerQuery->limitCount = outerLimitCount;
+ outerQuery->limitOption = outerLimitOption;
+
+ /*
+ * The outer query has no aggregates or window functions (those were
+ * extracted into the subquery), so only sub-links need to be reported.
+ */
+ outerQuery->hasSubLinks = checkExprHasSubLink(outerQual) ||
+ checkExprHasSubLink(outerLimitOffset) ||
+ checkExprHasSubLink(outerLimitCount);
+
+ assign_query_collations(opstate, outerQuery);
+
+ free_parsestate(opstate);
+
+ return outerQuery;
+}
+
/*
* transformSelectStmt -
@@ -1424,6 +1875,8 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
Query *qry = makeNode(Query);
Node *qual;
ListCell *l;
+ bool hasQualify = (stmt->qualifyClause != NULL);
+ Node *qualifyExpr = NULL;
qry->commandType = CMD_SELECT;
@@ -1480,6 +1933,13 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
* transformGroupClause and transformDistinctClause need the results. Note
* that these functions can also change the targetList, so it's passed to
* them by reference.
+ *
+ * When a QUALIFY clause is present, ORDER BY/DISTINCT/LIMIT are logically
+ * evaluated after QUALIFY and so belong to the outer query that
+ * rewriteQualifyQuery() builds. We still transform them here, against
+ * the inner query's scope, so that they can reference input columns and
+ * select-list aliases as in any other query; rewriteQualifyQuery() then
+ * lifts the resulting clauses out to the outer query.
*/
qry->sortClause = transformSortClause(pstate,
stmt->sortClause,
@@ -1529,6 +1989,42 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
stmt->limitOption);
qry->limitOption = stmt->limitOption;
+ /*
+ * Transform the QUALIFY condition, if any. This must happen before
+ * transformWindowDefinitions() so that window functions appearing only in
+ * QUALIFY get their inline window specifications registered and turned
+ * into WindowClauses. QUALIFY may reference select-list aliases, so we
+ * install a post-columnref hook that resolves a bare name to a
+ * select-list alias.
+ *
+ * The resolved condition is appended to the target list as a resjunk
+ * entry so that parseCheckAggregates() validates it like a select-list
+ * item; it is removed and decomposed into the outer query's WHERE clause
+ * by rewriteQualifyQuery() below.
+ */
+ if (hasQualify)
+ {
+ QualifyHookState qstate;
+
+ qstate.targetList = qry->targetList;
+ qstate.prev_hook = pstate->p_post_columnref_hook;
+ qstate.prev_hook_state = pstate->p_ref_hook_state;
+ pstate->p_post_columnref_hook = qualifyPostColumnRefHook;
+ pstate->p_ref_hook_state = &qstate;
+
+ qualifyExpr = transformWhereClause(pstate, stmt->qualifyClause,
+ EXPR_KIND_QUALIFY, "QUALIFY");
+
+ pstate->p_post_columnref_hook = qstate.prev_hook;
+ pstate->p_ref_hook_state = qstate.prev_hook_state;
+
+ qry->targetList = lappend(qry->targetList,
+ makeTargetEntry((Expr *) qualifyExpr,
+ list_length(qry->targetList) + 1,
+ NULL,
+ true));
+ }
+
/* transform window clauses after we have seen all window functions */
qry->windowClause = transformWindowDefinitions(pstate,
pstate->p_windowdefs,
@@ -1559,6 +2055,14 @@ transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
parseCheckAggregates(pstate, qry);
+ /*
+ * If a QUALIFY clause was present, wrap the query just built (the inner
+ * query) in an outer query whose WHERE clause is the QUALIFY condition,
+ * and process the deferred ORDER BY/DISTINCT/LIMIT clauses against it.
+ */
+ if (hasQualify)
+ return rewriteQualifyQuery(pstate, qry, qualifyExpr);
+
return qry;
}
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 0563453fe24..92ec17f870d 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -529,7 +529,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <node> TableElement TypedTableElement ConstraintElem DomainConstraintElem TableFuncElement
%type <node> columnDef columnOptions optionalPeriodName
%type <defelt> def_elem reloption_elem old_aggr_elem operator_def_elem
-%type <node> def_arg columnElem where_clause where_or_current_clause
+%type <node> def_arg columnElem where_clause qualify_clause where_or_current_clause
a_expr b_expr c_expr AexprConst indirection_el opt_slice_bound
columnref having_clause func_table xmltable array_expr
OptWhereClause operator_def_arg
@@ -780,7 +780,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
- QUOTE QUOTES
+ QUALIFY QUOTE QUOTES
RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPACK REPEATABLE REPLACE REPLICA
@@ -13211,7 +13211,7 @@ select_clause:
simple_select:
SELECT opt_all_clause opt_target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13223,11 +13223,12 @@ simple_select:
n->groupDistinct = ($7)->distinct;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| SELECT distinct_clause target_list
into_clause from_clause where_clause
- group_clause having_clause window_clause
+ group_clause having_clause window_clause qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13240,6 +13241,7 @@ simple_select:
n->groupDistinct = ($7)->distinct;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| values_clause { $$ = $1; }
@@ -14357,6 +14359,11 @@ where_clause:
| /*EMPTY*/ { $$ = NULL; }
;
+qualify_clause:
+ QUALIFY a_expr { $$ = $2; }
+ | /*EMPTY*/ { $$ = NULL; }
+ ;
+
/* variant for UPDATE and DELETE */
where_or_current_clause:
WHERE a_expr { $$ = $2; }
@@ -18583,6 +18590,7 @@ reserved_keyword:
| ORDER
| PLACING
| PRIMARY
+ | QUALIFY
| REFERENCES
| RETURNING
| SELECT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index a5424c9d24c..7c43b2e936f 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -407,6 +407,9 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ /* okay */
+ break;
case EXPR_KIND_POLICY:
if (isAgg)
err = _("aggregate functions are not allowed in policy expressions");
@@ -949,6 +952,7 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
err = _("window functions are not allowed in window definitions");
break;
case EXPR_KIND_SELECT_TARGET:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
case EXPR_KIND_INSERT_TARGET:
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 05a6b72d4c9..3a682243280 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -577,6 +577,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_COPY_WHERE:
case EXPR_KIND_GENERATED_COLUMN:
case EXPR_KIND_CYCLE_MARK:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
@@ -1805,6 +1806,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FROM_SUBSELECT:
case EXPR_KIND_FROM_FUNCTION:
case EXPR_KIND_WHERE:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
case EXPR_KIND_FILTER:
@@ -3159,6 +3161,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "function in FROM";
case EXPR_KIND_WHERE:
return "WHERE";
+ case EXPR_KIND_QUALIFY:
+ return "QUALIFY";
case EXPR_KIND_POLICY:
return "POLICY";
case EXPR_KIND_HAVING:
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index f75f5f2fbba..725eea86400 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -2744,6 +2744,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_WHERE:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ errkind = true;
+ break;
case EXPR_KIND_POLICY:
err = _("set-returning functions are not allowed in policy expressions");
break;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 0debcd193ab..3563cc6a467 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -2239,6 +2239,7 @@ typedef struct SelectStmt
bool groupDistinct; /* Is this GROUP BY DISTINCT? */
Node *havingClause; /* HAVING conditional-expression */
List *windowClause; /* WINDOW window_name AS (...), ... */
+ Node *qualifyClause; /* QUALIFY conditional-expression */
/*
* In a "leaf" node representing a VALUES list, the above fields are all
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 53ae96c0399..91e11d733e0 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -361,6 +361,7 @@ PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("qualify", QUALIFY, RESERVED_KEYWORD, AS_LABEL)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("quotes", QUOTES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f23e21f318b..0fca5121161 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -45,6 +45,7 @@ typedef enum ParseExprKind
EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
EXPR_KIND_WHERE, /* WHERE */
EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_QUALIFY, /* QUALIFY */
EXPR_KIND_FILTER, /* FILTER */
EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
diff --git a/src/test/regress/expected/qualify.out b/src/test/regress/expected/qualify.out
new file mode 100644
index 00000000000..ae55a556449
--- /dev/null
+++ b/src/test/regress/expected/qualify.out
@@ -0,0 +1,1122 @@
+--
+-- QUALIFY clause tests
+--
+CREATE TEMPORARY TABLE empsalary (
+ depname varchar,
+ empno bigint,
+ salary int,
+ enroll_date date
+);
+INSERT INTO empsalary VALUES
+('develop', 10, 5200, '2007-08-01'),
+('sales', 1, 5000, '2006-10-01'),
+('personnel', 5, 3500, '2007-12-10'),
+('sales', 4, 4800, '2007-08-08'),
+('personnel', 2, 3900, '2006-12-23'),
+('develop', 7, 4200, '2008-01-01'),
+('develop', 9, 4500, '2008-01-01'),
+('sales', 3, 4800, '2007-08-01'),
+('develop', 8, 6000, '2006-10-01'),
+('develop', 11, 5200, '2007-08-15');
+--
+-- Basic QUALIFY functionality
+--
+-- Simple QUALIFY with inline window function
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rank
+-----------+-------+--------+------
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+-- QUALIFY with named window
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rank
+-----------+-------+--------+------
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+--
+-- Alias resolution tests
+--
+-- Reference alias defined in SELECT
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2
+ORDER BY depname, salary DESC, empno;
+ depname | empno | salary | rnk
+-----------+-------+--------+-----
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+ personnel | 2 | 3900 | 1
+ personnel | 5 | 3500 | 2
+ sales | 1 | 5000 | 1
+ sales | 3 | 4800 | 2
+ sales | 4 | 4800 | 2
+(8 rows)
+
+-- Reference alias with row_number
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 < 3)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- Multiple aliases
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: ((pg_qualify.rn = 1) OR (pg_qualify.rnk <= 2))
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2
+ORDER BY depname, salary DESC;
+ depname | empno | salary | rn | rnk
+-----------+-------+--------+----+-----
+ develop | 8 | 6000 | 1 | 1
+ develop | 10 | 5200 | 2 | 2
+ develop | 11 | 5200 | 3 | 2
+ personnel | 2 | 3900 | 1 | 1
+ personnel | 5 | 3500 | 2 | 2
+ sales | 1 | 5000 | 1 | 1
+ sales | 4 | 4800 | 2 | 2
+ sales | 3 | 4800 | 3 | 2
+(8 rows)
+
+--
+-- Run condition optimization tests
+--
+-- row_number with < operator (should use run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 < 3)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- row_number with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+ QUERY PLAN
+---------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+ empno | rn
+-------+----
+ 1 | 1
+ 2 | 2
+(2 rows)
+
+-- rank with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- dense_rank with = operator (should convert to <= for run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.dr = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (dense_rank() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+ empno | salary | dr
+-------+--------+----
+ 8 | 6000 | 1
+(1 row)
+
+-- count(*) with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+ QUERY PLAN
+---------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary)
+ Run Condition: (count(*) OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+ empno | salary | c
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 3
+ 11 | 5200 | 3
+(3 rows)
+
+--
+-- WHERE pushdown tests
+-- Quals on PARTITION BY columns without window functions can be pushed to WHERE
+--
+-- depname is in PARTITION BY, should be pushed to WHERE (SeqScan filter)
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop';
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'develop'::text)
+(7 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop'
+ORDER BY salary DESC;
+ depname | empno | salary | rnk
+---------+-------+--------+-----
+ develop | 8 | 6000 | 1
+ develop | 10 | 5200 | 2
+ develop | 11 | 5200 | 2
+(3 rows)
+
+-- Mixed: depname pushed to WHERE, rank condition stays as run condition
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rnk = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'sales'::text)
+(9 rows)
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+ depname | empno | salary | rnk
+---------+-------+--------+-----
+ sales | 1 | 5000 | 1
+(1 row)
+
+--
+-- QUALIFY without window function in SELECT list
+-- The window function appears only in QUALIFY
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify4 = 1)
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+ depname | empno | salary
+-----------+-------+--------
+ develop | 8 | 6000
+ personnel | 2 | 3900
+ sales | 1 | 5000
+(3 rows)
+
+-- With PARTITION BY column filter pushed down
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify4 = 1)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+ Filter: ((depname)::text = 'develop'::text)
+(9 rows)
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+ depname | empno | salary
+---------+-------+--------
+ develop | 8 | 6000
+(1 row)
+
+--
+-- Multiple window functions with different windows
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: ((pg_qualify.rn_asc = 1) OR (pg_qualify.rn_desc = 1))
+ -> WindowAgg
+ Window: w2 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Incremental Sort
+ Sort Key: empsalary.depname, empsalary.salary
+ Presorted Key: empsalary.depname
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(12 rows)
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1
+ORDER BY depname, empno;
+ depname | empno | salary | rn_asc | rn_desc
+-----------+-------+--------+--------+---------
+ develop | 7 | 4200 | 1 | 5
+ develop | 8 | 6000 | 5 | 1
+ personnel | 2 | 3900 | 2 | 1
+ personnel | 5 | 3500 | 1 | 2
+ sales | 1 | 5000 | 3 | 1
+ sales | 4 | 4800 | 1 | 2
+(6 rows)
+
+--
+-- QUALIFY with aggregate and window functions
+--
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+ QUERY PLAN
+-----------------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ -> WindowAgg
+ Window: w1 AS (ORDER BY (sum(empsalary.salary)) ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 2)
+ -> Sort
+ Sort Key: (sum(empsalary.salary)) DESC
+ -> HashAggregate
+ Group Key: empsalary.depname
+ -> Seq Scan on empsalary
+(9 rows)
+
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+ depname | total | rnk
+---------+-------+-----
+ develop | 25100 | 1
+ sales | 14600 | 2
+(2 rows)
+
+--
+-- QUALIFY in a grouped query without window functions.
+-- The condition is validated like a SELECT-list item, so aggregates and
+-- grouping columns are allowed (and behave as HAVING would).
+--
+-- Aggregate used directly in QUALIFY filters groups like HAVING
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY count(*) > 2
+ORDER BY depname;
+ depname | c
+---------+---
+ develop | 5
+ sales | 3
+(2 rows)
+
+-- A grouping column may be referenced directly in QUALIFY
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY depname <> 'sales'
+ORDER BY depname;
+ depname | c
+-----------+---
+ develop | 5
+ personnel | 2
+(2 rows)
+
+--
+-- Comparison with equivalent subquery (results should match)
+--
+-- Subquery version
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- QUALIFY version (should produce same results)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | r
+-------+--------+---
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+--
+-- QUALIFY with different comparison operators
+--
+-- Greater than (no run condition optimization for increasing functions)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn > 7)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7
+ORDER BY empno;
+ empno | rn
+-------+----
+ 9 | 8
+ 10 | 9
+ 11 | 10
+(3 rows)
+
+-- Equality
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn = 5)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+ empno | rn
+-------+----
+ 5 | 5
+(1 row)
+
+-- BETWEEN (should keep as filter)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5;
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn >= 3)
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5
+ORDER BY empno;
+ empno | rn
+-------+----
+ 3 | 3
+ 4 | 4
+ 5 | 5
+(3 rows)
+
+-- IN list
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5);
+ QUERY PLAN
+---------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rn = ANY ('{1,3,5}'::bigint[]))
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.empno ROWS UNBOUNDED PRECEDING)
+ -> Sort
+ Sort Key: empsalary.empno
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5)
+ORDER BY empno;
+ empno | rn
+-------+----
+ 1 | 1
+ 3 | 3
+ 5 | 5
+(3 rows)
+
+--
+-- QUALIFY with expressions
+--
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+ empno | salary | rn
+-------+--------+----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 3
+ 1 | 5000 | 4
+ 4 | 4800 | 5
+(5 rows)
+
+--
+-- Error cases
+--
+-- Aggregate in QUALIFY without GROUP BY: just as in the SELECT list, the
+-- non-aggregated output columns make this an error (must appear in GROUP BY).
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY sum(salary) > 5000;
+ERROR: column "empsalary.depname" must appear in the GROUP BY clause or be used in an aggregate function
+LINE 1: SELECT depname, empno, salary
+ ^
+-- QUALIFY in a grouped query referencing an ungrouped column (should error,
+-- just as such a reference would in the SELECT list)
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY salary > 100;
+ERROR: column "empsalary.salary" must appear in the GROUP BY clause or be used in an aggregate function
+LINE 4: QUALIFY salary > 100;
+ ^
+-- QUALIFY with set-returning function (should error)
+SELECT empno, salary
+FROM empsalary
+QUALIFY generate_series(1, 3) > 1;
+ERROR: set-returning functions are not allowed in QUALIFY
+LINE 3: QUALIFY generate_series(1, 3) > 1;
+ ^
+--
+-- QUALIFY in different query structures
+--
+-- With DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+ QUERY PLAN
+----------------------------------------------------------------------------------------------
+ Unique
+ -> Incremental Sort
+ Sort Key: pg_qualify.depname, pg_qualify.top_emp
+ Presorted Key: pg_qualify.depname
+ -> Subquery Scan on pg_qualify
+ Filter: (pg_qualify.qualify3 = 1)
+ -> WindowAgg
+ Window: w1 AS (PARTITION BY empsalary.depname ORDER BY empsalary.salary)
+ Run Condition: (row_number() OVER w1 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname, empsalary.salary DESC
+ -> Seq Scan on empsalary
+(12 rows)
+
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+ depname | top_emp
+-----------+---------
+ develop | 8
+ personnel | 2
+ sales | 1
+(3 rows)
+
+-- With ORDER BY
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (rank() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(6 rows)
+
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3
+ORDER BY salary DESC, empno;
+ empno | salary | rnk
+-------+--------+-----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 2
+(3 rows)
+
+-- With LIMIT (QUALIFY is evaluated before LIMIT)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+LIMIT 3;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ Limit
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 5)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(7 rows)
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+ORDER BY salary DESC
+LIMIT 3;
+ empno | salary | rn
+-------+--------+----
+ 8 | 6000 | 1
+ 10 | 5200 | 2
+ 11 | 5200 | 3
+(3 rows)
+
+--
+-- Verify evaluation order: QUALIFY happens after window functions, before DISTINCT
+--
+-- This should first compute row_number, then filter, then apply DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+ QUERY PLAN
+----------------------------------------------------------------------------
+ HashAggregate
+ Group Key: empsalary.salary, row_number() OVER w1
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.salary ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w1 <= 3)
+ -> Sort
+ Sort Key: empsalary.salary DESC
+ -> Seq Scan on empsalary
+(8 rows)
+
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+ salary | rn
+--------+----
+ 5200 | 2
+ 5200 | 3
+ 6000 | 1
+(3 rows)
+
+-- QUALIFY with FILTERS over window function
+EXPLAIN(COSTS OFF) SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+ QUERY PLAN
+-----------------------------------------------------------------------------
+ Subquery Scan on pg_qualify
+ Filter: (pg_qualify.rank = 1)
+ -> WindowAgg
+ Window: w2 AS (ORDER BY empsalary.depname ROWS UNBOUNDED PRECEDING)
+ Run Condition: (row_number() OVER w2 <= 1)
+ -> Sort
+ Sort Key: empsalary.depname
+ -> WindowAgg
+ Window: w1 AS (ORDER BY empsalary.depname)
+ -> Sort
+ Sort Key: empsalary.depname DESC
+ -> HashAggregate
+ Group Key: empsalary.depname
+ -> Seq Scan on empsalary
+(14 rows)
+
+SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+ sum | rank | filtered_sum | depname
+-------+------+--------------+---------
+ 25100 | 1 | 22600 | develop
+(1 row)
+
+--
+-- Aggregate functions directly in QUALIFY
+-- (allowed in a grouped query, the same as in the SELECT list / HAVING)
+--
+-- Aggregate condition over the group
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000;
+ QUERY PLAN
+-------------------------------------------------
+ Subquery Scan on pg_qualify
+ -> HashAggregate
+ Group Key: empsalary.depname
+ Filter: (sum(empsalary.salary) > 15000)
+ -> Seq Scan on empsalary
+(5 rows)
+
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000
+ORDER BY depname;
+ depname | total
+---------+-------
+ develop | 25100
+(1 row)
+
+-- Aggregate and window function combined in QUALIFY
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY rank() OVER (ORDER BY sum(salary) DESC) = 1
+ORDER BY depname;
+ depname | total
+---------+-------
+ develop | 25100
+(1 row)
+
+-- Whole-table aggregate (single group)
+SELECT sum(salary) AS s
+FROM empsalary
+QUALIFY sum(salary) > 1000;
+ s
+-------
+ 47100
+(1 row)
+
+--
+-- Name resolution tests
+--
+-- An input column takes precedence over a same-named select-list alias
+-- "salary" in QUALIFY is the input column (> 4000 keeps most rows), not the
+-- alias (which is 0 and would keep none)
+SELECT empno, (empno * 0) AS salary
+FROM empsalary
+QUALIFY salary > 4000
+ORDER BY empno;
+ empno | salary
+-------+--------
+ 1 | 0
+ 3 | 0
+ 4 | 0
+ 7 | 0
+ 8 | 0
+ 9 | 0
+ 10 | 0
+ 11 | 0
+(8 rows)
+
+-- QUALIFY referecing columns that not on output result
+-- Same column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY salary;
+ depname
+-----------
+ personnel
+ personnel
+ develop
+ develop
+ sales
+ sales
+ sales
+ develop
+ develop
+ develop
+(10 rows)
+
+-- Different column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY enroll_date;
+ depname
+-----------
+ sales
+ develop
+ personnel
+ sales
+ develop
+ sales
+ develop
+ personnel
+ develop
+ develop
+(10 rows)
+
+--
+-- Name resolution error cases
+--
+-- A non-deterministic alias expression cannot be referenced from QUALIFY
+SELECT empno, (random() < 2)::int AS r
+FROM empsalary
+QUALIFY r = 1;
+ERROR: QUALIFY cannot reference output column "r" whose expression is non-deterministic
+LINE 3: QUALIFY r = 1;
+ ^
+-- An ambiguous alias reference is rejected
+SELECT empno AS x, salary AS x,
+ row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY x > 0;
+ERROR: column reference "x" is ambiguous
+LINE 4: QUALIFY x > 0;
+ ^
+-- A name that is neither an input column nor a select-list alias
+SELECT empno
+FROM empsalary
+QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+ERROR: column "nosuchcol" does not exist
+LINE 3: QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+ ^
+--
+-- QUALIFY without any window function: a general post-SELECT filter
+--
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000;
+ QUERY PLAN
+----------------------------------
+ Seq Scan on empsalary
+ Filter: ((salary * 2) > 10000)
+(2 rows)
+
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000
+ORDER BY empno;
+ empno | salary | new_salary
+-------+--------+------------
+ 8 | 6000 | 12000
+ 10 | 5200 | 10400
+ 11 | 5200 | 10400
+(3 rows)
+
+--
+-- QUALIFY in other query structures
+--
+-- In the arms of a set operation
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary) = 1
+UNION ALL
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary DESC) = 1
+ORDER BY empno;
+ empno
+-------
+ 5
+ 8
+(2 rows)
+
+-- In a subquery that carries an outer reference
+SELECT depname,
+ (SELECT empno FROM empsalary e2
+ WHERE e2.depname = e1.depname
+ QUALIFY row_number() OVER (ORDER BY salary DESC) = 1) AS top_emp
+FROM (SELECT DISTINCT depname FROM empsalary) e1
+ORDER BY depname;
+ depname | top_emp
+-----------+---------
+ develop | 8
+ personnel | 2
+ sales | 1
+(3 rows)
+
+-- Combined with row-level locking (the lock applies to the base table)
+SELECT empno FROM empsalary
+QUALIFY salary > 5000
+ORDER BY empno
+FOR UPDATE;
+ empno
+-------
+ 8
+ 10
+ 11
+(3 rows)
+
+--
+-- Cleanup
+--
+DROP TABLE empsalary;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 75063f87a4a..dfb59895185 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -102,7 +102,7 @@ test: publication subscription
# Another group of parallel tests
# select_views depends on create_view
# ----------
-test: select_views portals_p2 foreign_key dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite
+test: select_views portals_p2 foreign_key dependency guc bitmapops combocid tsearch tsdicts foreign_data window qualify xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite
# ----------
# Another group of parallel tests (JSON related)
diff --git a/src/test/regress/sql/qualify.sql b/src/test/regress/sql/qualify.sql
new file mode 100644
index 00000000000..c9bf99e23fe
--- /dev/null
+++ b/src/test/regress/sql/qualify.sql
@@ -0,0 +1,563 @@
+--
+-- QUALIFY clause tests
+--
+
+CREATE TEMPORARY TABLE empsalary (
+ depname varchar,
+ empno bigint,
+ salary int,
+ enroll_date date
+);
+
+INSERT INTO empsalary VALUES
+('develop', 10, 5200, '2007-08-01'),
+('sales', 1, 5000, '2006-10-01'),
+('personnel', 5, 3500, '2007-12-10'),
+('sales', 4, 4800, '2007-08-08'),
+('personnel', 2, 3900, '2006-12-23'),
+('develop', 7, 4200, '2008-01-01'),
+('develop', 9, 4500, '2008-01-01'),
+('sales', 3, 4800, '2007-08-01'),
+('develop', 8, 6000, '2006-10-01'),
+('develop', 11, 5200, '2007-08-15');
+
+--
+-- Basic QUALIFY functionality
+--
+
+-- Simple QUALIFY with inline window function
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC)
+FROM empsalary
+QUALIFY rank() OVER (PARTITION BY depname ORDER BY salary DESC) <= 2
+ORDER BY depname, salary DESC, empno;
+
+-- QUALIFY with named window
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER w
+FROM empsalary
+WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
+QUALIFY rank() OVER w <= 2
+ORDER BY depname, salary DESC, empno;
+
+--
+-- Alias resolution tests
+--
+
+-- Reference alias defined in SELECT
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2
+ORDER BY depname, salary DESC, empno;
+
+-- Reference alias with row_number
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+-- Multiple aliases
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2;
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rn = 1 OR rnk <= 2
+ORDER BY depname, salary DESC;
+
+--
+-- Run condition optimization tests
+--
+
+-- row_number with < operator (should use run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn < 3;
+
+-- row_number with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn <= 2;
+
+-- rank with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+-- dense_rank with = operator (should convert to <= for run condition)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+
+SELECT empno, salary, dense_rank() OVER (ORDER BY salary DESC) AS dr
+FROM empsalary
+QUALIFY dr = 1;
+
+-- count(*) with <= operator
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+
+SELECT empno, salary, count(*) OVER (ORDER BY salary DESC) AS c
+FROM empsalary
+QUALIFY c <= 3;
+
+--
+-- WHERE pushdown tests
+-- Quals on PARTITION BY columns without window functions can be pushed to WHERE
+--
+
+-- depname is in PARTITION BY, should be pushed to WHERE (SeqScan filter)
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop';
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 2 AND depname = 'develop'
+ORDER BY salary DESC;
+
+-- Mixed: depname pushed to WHERE, rank condition stays as run condition
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+
+SELECT depname, empno, salary,
+ rank() OVER (PARTITION BY depname ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY depname = 'sales' AND rnk = 1;
+
+--
+-- QUALIFY without window function in SELECT list
+-- The window function appears only in QUALIFY
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+
+-- With PARTITION BY column filter pushed down
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ AND depname = 'develop';
+
+--
+-- Multiple window functions with different windows
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1;
+
+SELECT depname, empno, salary,
+ row_number() OVER (PARTITION BY depname ORDER BY salary) AS rn_asc,
+ row_number() OVER (PARTITION BY depname ORDER BY salary DESC) AS rn_desc
+FROM empsalary
+QUALIFY rn_asc = 1 OR rn_desc = 1
+ORDER BY depname, empno;
+
+--
+-- QUALIFY with aggregate and window functions
+--
+
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+
+SELECT depname, sum(salary) AS total,
+ rank() OVER (ORDER BY sum(salary) DESC) AS rnk
+FROM empsalary
+GROUP BY depname
+QUALIFY rnk <= 2;
+
+--
+-- QUALIFY in a grouped query without window functions.
+-- The condition is validated like a SELECT-list item, so aggregates and
+-- grouping columns are allowed (and behave as HAVING would).
+--
+
+-- Aggregate used directly in QUALIFY filters groups like HAVING
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY count(*) > 2
+ORDER BY depname;
+
+-- A grouping column may be referenced directly in QUALIFY
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY depname <> 'sales'
+ORDER BY depname;
+
+--
+-- Comparison with equivalent subquery (results should match)
+--
+
+-- Subquery version
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3;
+
+SELECT * FROM
+ (SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+ FROM empsalary) emp
+WHERE r <= 3
+ORDER BY salary DESC, empno;
+
+-- QUALIFY version (should produce same results)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3;
+
+SELECT empno, salary, rank() OVER (ORDER BY salary DESC) AS r
+FROM empsalary
+QUALIFY r <= 3
+ORDER BY salary DESC, empno;
+
+--
+-- QUALIFY with different comparison operators
+--
+
+-- Greater than (no run condition optimization for increasing functions)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn > 7
+ORDER BY empno;
+
+-- Equality
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn = 5;
+
+-- BETWEEN (should keep as filter)
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5;
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn BETWEEN 3 AND 5
+ORDER BY empno;
+
+-- IN list
+EXPLAIN (COSTS OFF)
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5);
+
+SELECT empno, row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY rn IN (1, 3, 5)
+ORDER BY empno;
+
+--
+-- QUALIFY with expressions
+--
+
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 10 / 2;
+
+--
+-- Error cases
+--
+
+-- Aggregate in QUALIFY without GROUP BY: just as in the SELECT list, the
+-- non-aggregated output columns make this an error (must appear in GROUP BY).
+SELECT depname, empno, salary
+FROM empsalary
+QUALIFY sum(salary) > 5000;
+
+-- QUALIFY in a grouped query referencing an ungrouped column (should error,
+-- just as such a reference would in the SELECT list)
+SELECT depname, count(*) AS c
+FROM empsalary
+GROUP BY depname
+QUALIFY salary > 100;
+
+-- QUALIFY with set-returning function (should error)
+SELECT empno, salary
+FROM empsalary
+QUALIFY generate_series(1, 3) > 1;
+
+--
+-- QUALIFY in different query structures
+--
+
+-- With DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1;
+
+SELECT DISTINCT depname,
+ first_value(empno) OVER (PARTITION BY depname ORDER BY salary DESC) AS top_emp
+FROM empsalary
+QUALIFY row_number() OVER (PARTITION BY depname ORDER BY salary DESC) = 1
+ORDER BY depname;
+
+-- With ORDER BY
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3;
+
+SELECT empno, salary,
+ rank() OVER (ORDER BY salary DESC) AS rnk
+FROM empsalary
+QUALIFY rnk <= 3
+ORDER BY salary DESC, empno;
+
+-- With LIMIT (QUALIFY is evaluated before LIMIT)
+EXPLAIN (COSTS OFF)
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+LIMIT 3;
+
+SELECT empno, salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 5
+ORDER BY salary DESC
+LIMIT 3;
+
+--
+-- Verify evaluation order: QUALIFY happens after window functions, before DISTINCT
+--
+
+-- This should first compute row_number, then filter, then apply DISTINCT
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+
+SELECT DISTINCT salary,
+ row_number() OVER (ORDER BY salary DESC) AS rn
+FROM empsalary
+QUALIFY rn <= 3;
+
+-- QUALIFY with FILTERS over window function
+EXPLAIN(COSTS OFF) SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+
+SELECT sum(salary), row_number() OVER (ORDER BY depname) as rank, sum(
+ sum(salary) FILTER (WHERE enroll_date > '2007-01-01')
+) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum",
+ depname
+FROM empsalary GROUP BY depname QUALIFY rank = 1;
+
+--
+-- Aggregate functions directly in QUALIFY
+-- (allowed in a grouped query, the same as in the SELECT list / HAVING)
+--
+
+-- Aggregate condition over the group
+EXPLAIN (COSTS OFF)
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000;
+
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY sum(salary) > 15000
+ORDER BY depname;
+
+-- Aggregate and window function combined in QUALIFY
+SELECT depname, sum(salary) AS total
+FROM empsalary
+GROUP BY depname
+QUALIFY rank() OVER (ORDER BY sum(salary) DESC) = 1
+ORDER BY depname;
+
+-- Whole-table aggregate (single group)
+SELECT sum(salary) AS s
+FROM empsalary
+QUALIFY sum(salary) > 1000;
+
+--
+-- Name resolution tests
+--
+
+-- An input column takes precedence over a same-named select-list alias
+-- "salary" in QUALIFY is the input column (> 4000 keeps most rows), not the
+-- alias (which is 0 and would keep none)
+SELECT empno, (empno * 0) AS salary
+FROM empsalary
+QUALIFY salary > 4000
+ORDER BY empno;
+
+-- QUALIFY referecing columns that not on output result
+
+-- Same column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY salary;
+
+-- Different column
+SELECT depname FROM empsalary QUALIFY salary > 0 ORDER BY enroll_date;
+
+--
+-- Name resolution error cases
+--
+
+-- A non-deterministic alias expression cannot be referenced from QUALIFY
+SELECT empno, (random() < 2)::int AS r
+FROM empsalary
+QUALIFY r = 1;
+
+-- An ambiguous alias reference is rejected
+SELECT empno AS x, salary AS x,
+ row_number() OVER (ORDER BY empno) AS rn
+FROM empsalary
+QUALIFY x > 0;
+
+-- A name that is neither an input column nor a select-list alias
+SELECT empno
+FROM empsalary
+QUALIFY nosuchcol > row_number() OVER (ORDER BY empno);
+
+--
+-- QUALIFY without any window function: a general post-SELECT filter
+--
+
+EXPLAIN (COSTS OFF)
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000;
+
+SELECT empno, salary, salary * 2 as new_salary
+FROM empsalary
+QUALIFY new_salary > 10000
+ORDER BY empno;
+
+--
+-- QUALIFY in other query structures
+--
+
+-- In the arms of a set operation
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary) = 1
+UNION ALL
+SELECT empno FROM empsalary
+QUALIFY row_number() OVER (ORDER BY salary DESC) = 1
+ORDER BY empno;
+
+-- In a subquery that carries an outer reference
+SELECT depname,
+ (SELECT empno FROM empsalary e2
+ WHERE e2.depname = e1.depname
+ QUALIFY row_number() OVER (ORDER BY salary DESC) = 1) AS top_emp
+FROM (SELECT DISTINCT depname FROM empsalary) e1
+ORDER BY depname;
+
+-- Combined with row-level locking (the lock applies to the base table)
+SELECT empno FROM empsalary
+QUALIFY salary > 5000
+ORDER BY empno
+FOR UPDATE;
+
+--
+-- Cleanup
+--
+DROP TABLE empsalary;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 5d432074c2c..41ad1ab2a62 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2476,6 +2476,9 @@ QTNode
QUERYTYPE
QualCost
QualItem
+QualifyExtractContext
+QualifyHookState
+QualifyVarmapContext
Query
QueryCompletion
QueryDesc
--
2.50.1 (Apple Git-155)
v4-0001-Add-QUALIFY-clause.patch.nocfbot (text/plain, 86.2K) download
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
@ 2025-07-25 12:55 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-25 14:50 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
3 siblings, 1 reply; 41+ messages in thread
From: Matheus Alcantara @ 2025-07-25 12:55 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
On Mon Jul 21, 2025 at 7:11 PM -03, Vik Fearing wrote:
> That is my preferred grammar, thank you. I have not looked at the C
> code by this can be obtained with a syntax transformation. To wit:
>
>
> SELECT a, b, c
> FROM tab
> QUALIFY wf() OVER () = ?
>
>
> can be rewritten as:
>
>
> SELECT a, b, c
> FROM (
> SELECT a, b, c, wf() OVER () = ? AS qc
> FROM tab
> ) AS q
> WHERE qc
>
>
> and then let the optimizer take over. The standard does this kind of
> thing all over the place; I don't know what the postgres project's
> position on doing things like this are.
>
With this transformation users will see a Subquery plan node even if
it's not present on the original query, is that expected or it can be
confusing to users?
--
Matheus Alcantara
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 20:23 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Re: Proposal: QUALIFY clause Vik Fearing <vik@postgresfriends.org>
2025-07-25 12:55 ` Re: Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
@ 2025-07-25 14:50 ` Vik Fearing <vik@postgresfriends.org>
0 siblings, 0 replies; 41+ messages in thread
From: Vik Fearing @ 2025-07-25 14:50 UTC (permalink / raw)
To: Matheus Alcantara <matheusssilv97@gmail.com>; pgsql-hackers; +Cc: Peter Eisentraut <peter@eisentraut.org>
On 25/07/2025 14:55, Matheus Alcantara wrote:
> On Mon Jul 21, 2025 at 7:11 PM -03, Vik Fearing wrote:
>> SELECT a, b, c
>> FROM tab
>> QUALIFY wf() OVER () = ?
>>
>>
>> can be rewritten as:
>>
>>
>> SELECT a, b, c
>> FROM (
>> SELECT a, b, c, wf() OVER () = ? AS qc
>> FROM tab
>> ) AS q
>> WHERE qc
>>
>>
>> and then let the optimizer take over. The standard does this kind of
>> thing all over the place; I don't know what the postgres project's
>> position on doing things like this are.
> With this transformation users will see a Subquery plan node even if
> it's not present on the original query, is that expected or it can be
> confusing to users?
This is a definition technique, it does not need to be implemented as a
subquery.
--
Vik Fearing
^ permalink raw reply [nested|flat] 41+ messages in thread
* Re: Proposal: QUALIFY clause
@ 2025-12-05 12:55 Yannick Goetschel <Yannick.Goetschel@tradition.ch>
0 siblings, 0 replies; 41+ messages in thread
From: Yannick Goetschel @ 2025-12-05 12:55 UTC (permalink / raw)
To: pgsql-hackers
Hi Tom,
Thanks for the feedback.
If the syntax is like WHERE, there will be no way to do it without making QUALIFY a fully-reserved word. That will inevitably break more than zero applications.
You are right that QUALIFY functioning as a clause at the same level as WHERE / HAVING creates grammar conflicts if not reserved, particularly with column aliases.
However, I'd like to argue that the utility of QUALIFY justifies this cost, and its status as a de-facto industry standard mitigates the lack of formal standardization.
1. De-facto Standardization & Ergonomics While QUALIFY is not in the ISO SQL standard, it has been adopted by major analytical databases including Snowflake, BigQuery, Databricks, and Teradata. Users migrating from or working across these systems expect this functionality. The ergonomic benefit is significant: it removes the need for a full subquery wrapper just to filter on window functions, which is a very common pattern in analytical queries. This improves query readability and writability substantially.
2. Keyword Reservation Consistency Similar clauses like WINDOW and HAVING are also fully reserved keywords in PostgreSQL to avoid similar ambiguity. Treating QUALIFY consistently with these clauses seems logical from a language design perspective, even if it adds one more reserved word.
3. Implementation & Testing details I have implemented QUALIFY as a new clause processed after WINDOW but before DISTINCT and ORDER BY, effectively acting as a filter on the result of window functions.
Key implementation details:
* Execution Order: The clause is evaluated after window functions are computed, allowing predicates on window function results without subqueries.
* Alias Support: Access to output column aliases (e.g. SELECT ... AS alias ... QUALIFY alias > 10) is supported, resolving a major pain point.
Testing coverage (src/test/regress/sql/qualify.sql):
* Basic filtering on window functions.
* Integration with WHERE, GROUP BY, and HAVING clauses.
* Support for window aliases (WINDOW w AS ...).
* Verify interactions with aggregates (allowed if logically consistent with grouping).
* Resolution of ambiguous aliases.
1. Path Forward If the community feels strongly that a full reservation is a blocker, I am open to exploring if we can make it unreserved or col_name_keyword with some grammar adjustments (e.g. relying on position after WINDOW/HAVING), though as you noted, this risks edge-case ambiguities.
Given its widespread adoption elsewhere, I believe QUALIFY is the "correct" keyword for this feature rather than a new term like REFINE.
Thoughts?
Please find attached a functional patch to implement the qualify clause.
Best regards,
Yannick
--
Yannick Goetschel
Head of Data Engineering
Compagnie Financière Tradition
D: +41 (0)21 343 52 52
E: yannick.goetschel@tradition.ch<mailto:yannick.goetschel@tradition.ch>
------------------------------------------------------------------------------
This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. postmaster@tradition.ch
Attachments:
qualify_v1.patch (application/octet-stream, 65.1K) download
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index c4fd646b999..868f3025d82 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -187,14 +187,16 @@ static RelOptInfo *create_window_paths(PlannerInfo *root,
PathTarget *output_target,
bool output_target_parallel_safe,
WindowFuncLists *wflists,
- List *activeWindows);
+ List *activeWindows,
+ Node *qualifyQual);
static void create_one_window_path(PlannerInfo *root,
RelOptInfo *window_rel,
Path *path,
PathTarget *input_target,
PathTarget *output_target,
WindowFuncLists *wflists,
- List *activeWindows);
+ List *activeWindows,
+ Node *qualifyQual);
static RelOptInfo *create_distinct_paths(PlannerInfo *root,
RelOptInfo *input_rel,
PathTarget *target);
@@ -1849,7 +1851,8 @@ grouping_planner(PlannerInfo *root, double tuple_fraction,
sort_input_target,
sort_input_target_parallel_safe,
wflists,
- activeWindows);
+ activeWindows,
+ parse->qualifyQual);
/* Fix things up if sort_input_target contains SRFs */
if (parse->hasTargetSRFs)
adjust_paths_for_srfs(root, current_rel,
@@ -4555,7 +4558,8 @@ create_window_paths(PlannerInfo *root,
PathTarget *output_target,
bool output_target_parallel_safe,
WindowFuncLists *wflists,
- List *activeWindows)
+ List *activeWindows,
+ Node *qualifyQual)
{
RelOptInfo *window_rel;
ListCell *lc;
@@ -4600,7 +4604,8 @@ create_window_paths(PlannerInfo *root,
input_target,
output_target,
wflists,
- activeWindows);
+ activeWindows,
+ qualifyQual);
}
/*
@@ -4642,12 +4647,20 @@ create_one_window_path(PlannerInfo *root,
PathTarget *input_target,
PathTarget *output_target,
WindowFuncLists *wflists,
- List *activeWindows)
+ List *activeWindows,
+ Node *qualifyQual)
{
PathTarget *window_target;
ListCell *l;
List *topqual = NIL;
+ /*
+ * If there's a QUALIFY clause, add it to topqual.
+ * The QUALIFY clause filters rows after all window functions are computed.
+ */
+ if (qualifyQual)
+ topqual = list_make1(qualifyQual);
+
/*
* Since each window clause could require a different sort order, we stack
* up a WindowAgg node for each clause, with sort steps between them as
diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c
index 7843a0c857e..e4c58c082ce 100644
--- a/src/backend/parser/analyze.c
+++ b/src/backend/parser/analyze.c
@@ -1398,149 +1398,162 @@ count_rowexpr_columns(ParseState *pstate, Node *expr)
*/
static Query *
transformSelectStmt(ParseState *pstate, SelectStmt *stmt,
- SelectStmtPassthrough *passthru)
+ SelectStmtPassthrough *passthru)
{
- Query *qry = makeNode(Query);
- Node *qual;
- ListCell *l;
-
- qry->commandType = CMD_SELECT;
-
- /* process the WITH clause independently of all else */
- if (stmt->withClause)
- {
- qry->hasRecursive = stmt->withClause->recursive;
- qry->cteList = transformWithClause(pstate, stmt->withClause);
- qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
- }
-
- /* Complain if we get called from someplace where INTO is not allowed */
- if (stmt->intoClause)
- ereport(ERROR,
- (errcode(ERRCODE_SYNTAX_ERROR),
- errmsg("SELECT ... INTO is not allowed here"),
- parser_errposition(pstate,
- exprLocation((Node *) stmt->intoClause))));
-
- /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
- pstate->p_locking_clause = stmt->lockingClause;
-
- /* make WINDOW info available for window functions, too */
- pstate->p_windowdefs = stmt->windowClause;
-
- /* process the FROM clause */
- transformFromClause(pstate, stmt->fromClause);
-
- /* transform targetlist */
- qry->targetList = transformTargetList(pstate, stmt->targetList,
- EXPR_KIND_SELECT_TARGET);
-
- /*
- * If we're within a PLAssignStmt, do further transformation of the
- * targetlist; that has to happen before we consider sorting or grouping.
- * Otherwise, mark column origins (which are useless in a PLAssignStmt).
- */
- if (passthru)
- qry->targetList = transformPLAssignStmtTarget(pstate, qry->targetList,
- passthru);
- else
- markTargetListOrigins(pstate, qry->targetList);
-
- /* transform WHERE */
- qual = transformWhereClause(pstate, stmt->whereClause,
- EXPR_KIND_WHERE, "WHERE");
-
- /* initial processing of HAVING clause is much like WHERE clause */
- qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
- EXPR_KIND_HAVING, "HAVING");
-
- /*
- * Transform sorting/grouping stuff. Do ORDER BY first because both
- * transformGroupClause and transformDistinctClause need the results. Note
- * that these functions can also change the targetList, so it's passed to
- * them by reference.
- */
- qry->sortClause = transformSortClause(pstate,
- stmt->sortClause,
- &qry->targetList,
- EXPR_KIND_ORDER_BY,
- false /* allow SQL92 rules */ );
-
- qry->groupClause = transformGroupClause(pstate,
- stmt->groupClause,
- stmt->groupByAll,
- &qry->groupingSets,
- &qry->targetList,
- qry->sortClause,
- EXPR_KIND_GROUP_BY,
- false /* allow SQL92 rules */ );
- qry->groupDistinct = stmt->groupDistinct;
- qry->groupByAll = stmt->groupByAll;
-
- if (stmt->distinctClause == NIL)
- {
- qry->distinctClause = NIL;
- qry->hasDistinctOn = false;
- }
- else if (linitial(stmt->distinctClause) == NULL)
- {
- /* We had SELECT DISTINCT */
- qry->distinctClause = transformDistinctClause(pstate,
- &qry->targetList,
- qry->sortClause,
- false);
- qry->hasDistinctOn = false;
- }
- else
- {
- /* We had SELECT DISTINCT ON */
- qry->distinctClause = transformDistinctOnClause(pstate,
- stmt->distinctClause,
- &qry->targetList,
- qry->sortClause);
- qry->hasDistinctOn = true;
- }
-
- /* transform LIMIT */
- qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
- EXPR_KIND_OFFSET, "OFFSET",
- stmt->limitOption);
- qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
- EXPR_KIND_LIMIT, "LIMIT",
- stmt->limitOption);
- qry->limitOption = stmt->limitOption;
-
- /* transform window clauses after we have seen all window functions */
- qry->windowClause = transformWindowDefinitions(pstate,
- pstate->p_windowdefs,
- &qry->targetList);
-
- /* resolve any still-unresolved output columns as being type text */
- if (pstate->p_resolve_unknowns)
- resolveTargetListUnknowns(pstate, qry->targetList);
-
- qry->rtable = pstate->p_rtable;
- qry->rteperminfos = pstate->p_rteperminfos;
- qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
-
- qry->hasSubLinks = pstate->p_hasSubLinks;
- qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
- qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
- qry->hasAggs = pstate->p_hasAggs;
-
- foreach(l, stmt->lockingClause)
- {
- transformLockingClause(pstate, qry,
- (LockingClause *) lfirst(l), false);
- }
-
- assign_query_collations(pstate, qry);
-
- /* this must be done after collations, for reliable comparison of exprs */
- if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
- parseCheckAggregates(pstate, qry);
-
- return qry;
+ Query *qry = makeNode(Query);
+ Node *qual;
+ ListCell *l;
+
+ qry->commandType = CMD_SELECT;
+
+ /* process the WITH clause independently of all else */
+ if (stmt->withClause)
+ {
+ qry->hasRecursive = stmt->withClause->recursive;
+ qry->cteList = transformWithClause(pstate, stmt->withClause);
+ qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
+ }
+
+ /* Complain if we get called from someplace where INTO is not allowed */
+ if (stmt->intoClause)
+ ereport(ERROR,
+ (errcode(ERRCODE_SYNTAX_ERROR),
+ errmsg("SELECT ... INTO is not allowed here"),
+ parser_errposition(pstate,
+ exprLocation((Node *) stmt->intoClause))));
+
+ /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
+ pstate->p_locking_clause = stmt->lockingClause;
+
+ /* make WINDOW info available for window functions, too */
+ pstate->p_windowdefs = stmt->windowClause;
+
+ /* process the FROM clause */
+ transformFromClause(pstate, stmt->fromClause);
+
+ /* transform targetlist */
+ qry->targetList = transformTargetList(pstate, stmt->targetList,
+ EXPR_KIND_SELECT_TARGET);
+ pstate->p_targetList = qry->targetList;
+
+ /*
+ * If we're within a PLAssignStmt, do further transformation of the
+ * targetlist; that has to happen before we consider sorting or grouping.
+ * Otherwise, mark column origins (which are useless in a PLAssignStmt).
+ */
+ if (passthru)
+ qry->targetList = transformPLAssignStmtTarget(pstate, qry->targetList,
+ passthru);
+ else
+ markTargetListOrigins(pstate, qry->targetList);
+
+ /* transform WHERE */
+ qual = transformWhereClause(pstate, stmt->whereClause,
+ EXPR_KIND_WHERE, "WHERE");
+
+ /* initial processing of HAVING clause is much like WHERE clause */
+ qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
+ EXPR_KIND_HAVING, "HAVING");
+
+ /*
+ * The QUALIFY clause is much like HAVING, but for window functions.
+ * Using EXPR_KIND_QUALIFY allows specific checks (e.g., allowing window funcs).
+ */
+ qry->qualifyQual = transformWhereClause(pstate, stmt->qualifyClause,
+ EXPR_KIND_QUALIFY, "QUALIFY");
+
+ /*
+ * Transform sorting/grouping stuff. Do ORDER BY first because both
+ * transformGroupClause and transformDistinctClause need the results. Note
+ * that these functions can also change the targetList, so it's passed to
+ * them by reference.
+ */
+ qry->sortClause = transformSortClause(pstate,
+ stmt->sortClause,
+ &qry->targetList,
+ EXPR_KIND_ORDER_BY,
+ false /* allow SQL92 rules */ );
+
+ qry->groupClause = transformGroupClause(pstate,
+ stmt->groupClause,
+ stmt->groupByAll,
+ &qry->groupingSets,
+ &qry->targetList,
+ qry->sortClause,
+ EXPR_KIND_GROUP_BY,
+ false /* allow SQL92 rules */ );
+ qry->groupDistinct = stmt->groupDistinct;
+ qry->groupByAll = stmt->groupByAll;
+
+ if (stmt->distinctClause == NIL)
+ {
+ qry->distinctClause = NIL;
+ qry->hasDistinctOn = false;
+ }
+ else if (linitial(stmt->distinctClause) == NULL)
+ {
+ /* We had SELECT DISTINCT */
+ qry->distinctClause = transformDistinctClause(pstate,
+ &qry->targetList,
+ qry->sortClause,
+ false);
+ qry->hasDistinctOn = false;
+ }
+ else
+ {
+ /* We had SELECT DISTINCT ON */
+ qry->distinctClause = transformDistinctOnClause(pstate,
+ stmt->distinctClause,
+ &qry->targetList,
+ qry->sortClause);
+ qry->hasDistinctOn = true;
+ }
+
+ /* transform LIMIT */
+ qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
+ EXPR_KIND_OFFSET, "OFFSET",
+ stmt->limitOption);
+ qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
+ EXPR_KIND_LIMIT, "LIMIT",
+ stmt->limitOption);
+ qry->limitOption = stmt->limitOption;
+
+ /*
+ * transform window clauses after we have seen all window functions.
+ * UPDATED: Pass the QUALIFY clause (stmt->qualifyClause) so it can be
+ * attached to the WindowClause if the planner expects it there.
+ */
+ qry->windowClause = transformWindowDefinitions(pstate,
+ pstate->p_windowdefs,
+ &qry->targetList,
+ qry->qualifyQual); /* <--- Added argument */
+
+ /* resolve any still-unresolved output columns as being type text */
+ if (pstate->p_resolve_unknowns)
+ resolveTargetListUnknowns(pstate, qry->targetList);
+
+ qry->rtable = pstate->p_rtable;
+ qry->rteperminfos = pstate->p_rteperminfos;
+ qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
+
+ qry->hasSubLinks = pstate->p_hasSubLinks;
+ qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
+ qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
+ qry->hasAggs = pstate->p_hasAggs;
+
+ foreach(l, stmt->lockingClause)
+ {
+ transformLockingClause(pstate, qry,
+ (LockingClause *) lfirst(l), false);
+ }
+
+ assign_query_collations(pstate, qry);
+
+ /* this must be done after collations, for reliable comparison of exprs */
+ if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
+ parseCheckAggregates(pstate, qry);
+
+ return qry;
}
/*
@@ -2014,7 +2027,7 @@ transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
assign_query_collations(pstate, qry);
/* this must be done after collations, for reliable comparison of exprs */
- if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
+ if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual || qry->qualifyQual)
parseCheckAggregates(pstate, qry);
return qry;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index c3a0a354a9c..817f2094bf7 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -318,6 +318,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <node> select_no_parens select_with_parens select_clause
simple_select values_clause
+ qualify_clause
PLpgSQL_Expr PLAssignStmt
%type <str> opt_single_name
@@ -767,7 +768,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROCEDURES PROGRAM PUBLICATION
- QUOTE QUOTES
+ QUALIFY QUOTE QUOTES
RANGE READ REAL REASSIGN RECURSIVE REF_P REFERENCES REFERENCING
REFRESH REINDEX RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
@@ -13050,6 +13051,7 @@ simple_select:
SELECT opt_all_clause opt_target_list
into_clause from_clause where_clause
group_clause having_clause window_clause
+ qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13062,11 +13064,13 @@ simple_select:
n->groupByAll = ($7)->all;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| SELECT distinct_clause target_list
into_clause from_clause where_clause
group_clause having_clause window_clause
+ qualify_clause
{
SelectStmt *n = makeNode(SelectStmt);
@@ -13080,6 +13084,7 @@ simple_select:
n->groupByAll = ($7)->all;
n->havingClause = $8;
n->windowClause = $9;
+ n->qualifyClause = $10;
$$ = (Node *) n;
}
| values_clause { $$ = $1; }
@@ -14202,6 +14207,13 @@ where_clause:
| /*EMPTY*/ { $$ = NULL; }
;
+qualify_clause:
+ QUALIFY a_expr
+ { $$ = $2; }
+ | /*EMPTY*/
+ { $$ = NULL; }
+ ;
+
/* variant for UPDATE and DELETE */
where_or_current_clause:
WHERE a_expr { $$ = $2; }
@@ -14217,7 +14229,6 @@ where_or_current_clause:
| /*EMPTY*/ { $$ = NULL; }
;
-
OptTableFuncElementList:
TableFuncElementList { $$ = $1; }
| /*EMPTY*/ { $$ = NIL; }
@@ -18349,6 +18360,7 @@ reserved_keyword:
| ORDER
| PLACING
| PRIMARY
+ | QUALIFY
| REFERENCES
| RETURNING
| SELECT
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index b8340557b34..39b66ac4cc1 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -414,6 +414,7 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
break;
case EXPR_KIND_HAVING:
+ case EXPR_KIND_QUALIFY:
/* okay */
break;
case EXPR_KIND_FILTER:
@@ -937,6 +938,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_HAVING:
errkind = true;
break;
+ case EXPR_KIND_QUALIFY:
+ /* okay */
+ break;
case EXPR_KIND_FILTER:
errkind = true;
break;
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index ca26f6f61f2..bf8abc620d2 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -2825,208 +2825,207 @@ transformSortClause(ParseState *pstate,
*/
List *
transformWindowDefinitions(ParseState *pstate,
- List *windowdefs,
- List **targetlist)
+ List *windowdefs,
+ List **targetlist,
+ Node *qualifyClause) /* <--- Added argument */
{
- List *result = NIL;
- Index winref = 0;
- ListCell *lc;
-
- foreach(lc, windowdefs)
- {
- WindowDef *windef = (WindowDef *) lfirst(lc);
- WindowClause *refwc = NULL;
- List *partitionClause;
- List *orderClause;
- Oid rangeopfamily = InvalidOid;
- Oid rangeopcintype = InvalidOid;
- WindowClause *wc;
-
- winref++;
-
- /*
- * Check for duplicate window names.
- */
- if (windef->name &&
- findWindowClause(result, windef->name) != NULL)
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("window \"%s\" is already defined", windef->name),
- parser_errposition(pstate, windef->location)));
-
- /*
- * If it references a previous window, look that up.
- */
- if (windef->refname)
- {
- refwc = findWindowClause(result, windef->refname);
- if (refwc == NULL)
- ereport(ERROR,
- (errcode(ERRCODE_UNDEFINED_OBJECT),
- errmsg("window \"%s\" does not exist",
- windef->refname),
- parser_errposition(pstate, windef->location)));
- }
-
- /*
- * Transform PARTITION and ORDER specs, if any. These are treated
- * almost exactly like top-level GROUP BY and ORDER BY clauses,
- * including the special handling of nondefault operator semantics.
- */
- orderClause = transformSortClause(pstate,
- windef->orderClause,
- targetlist,
- EXPR_KIND_WINDOW_ORDER,
- true /* force SQL99 rules */ );
- partitionClause = transformGroupClause(pstate,
- windef->partitionClause,
- false /* not GROUP BY ALL */ ,
- NULL,
- targetlist,
- orderClause,
- EXPR_KIND_WINDOW_PARTITION,
- true /* force SQL99 rules */ );
-
- /*
- * And prepare the new WindowClause.
- */
- wc = makeNode(WindowClause);
- wc->name = windef->name;
- wc->refname = windef->refname;
-
- /*
- * Per spec, a windowdef that references a previous one copies the
- * previous partition clause (and mustn't specify its own). It can
- * specify its own ordering clause, but only if the previous one had
- * none. It always specifies its own frame clause, and the previous
- * one must not have a frame clause. Yeah, it's bizarre that each of
- * these cases works differently, but SQL:2008 says so; see 7.11
- * <window clause> syntax rule 10 and general rule 1. The frame
- * clause rule is especially bizarre because it makes "OVER foo"
- * different from "OVER (foo)", and requires the latter to throw an
- * error if foo has a nondefault frame clause. Well, ours not to
- * reason why, but we do go out of our way to throw a useful error
- * message for such cases.
- */
- if (refwc)
- {
- if (partitionClause)
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("cannot override PARTITION BY clause of window \"%s\"",
- windef->refname),
- parser_errposition(pstate, windef->location)));
- wc->partitionClause = copyObject(refwc->partitionClause);
- }
- else
- wc->partitionClause = partitionClause;
- if (refwc)
- {
- if (orderClause && refwc->orderClause)
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("cannot override ORDER BY clause of window \"%s\"",
- windef->refname),
- parser_errposition(pstate, windef->location)));
- if (orderClause)
- {
- wc->orderClause = orderClause;
- wc->copiedOrder = false;
- }
- else
- {
- wc->orderClause = copyObject(refwc->orderClause);
- wc->copiedOrder = true;
- }
- }
- else
- {
- wc->orderClause = orderClause;
- wc->copiedOrder = false;
- }
- if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
- {
- /*
- * Use this message if this is a WINDOW clause, or if it's an OVER
- * clause that includes ORDER BY or framing clauses. (We already
- * rejected PARTITION BY above, so no need to check that.)
- */
- if (windef->name ||
- orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("cannot copy window \"%s\" because it has a frame clause",
- windef->refname),
- parser_errposition(pstate, windef->location)));
- /* Else this clause is just OVER (foo), so say this: */
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("cannot copy window \"%s\" because it has a frame clause",
- windef->refname),
- errhint("Omit the parentheses in this OVER clause."),
- parser_errposition(pstate, windef->location)));
- }
- wc->frameOptions = windef->frameOptions;
+ List *result = NIL;
+ Index winref = 0;
+ ListCell *lc;
+ Node *transformedQualify = NULL;
- /*
- * RANGE offset PRECEDING/FOLLOWING requires exactly one ORDER BY
- * column; check that and get its sort opfamily info.
- */
- if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
- (wc->frameOptions & (FRAMEOPTION_START_OFFSET |
- FRAMEOPTION_END_OFFSET)))
- {
- SortGroupClause *sortcl;
- Node *sortkey;
- CompareType rangecmptype;
-
- if (list_length(wc->orderClause) != 1)
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
- parser_errposition(pstate, windef->location)));
- sortcl = linitial_node(SortGroupClause, wc->orderClause);
- sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
- /* Find the sort operator in pg_amop */
- if (!get_ordering_op_properties(sortcl->sortop,
- &rangeopfamily,
- &rangeopcintype,
- &rangecmptype))
- elog(ERROR, "operator %u is not a valid ordering operator",
- sortcl->sortop);
- /* Record properties of sort ordering */
- wc->inRangeColl = exprCollation(sortkey);
- wc->inRangeAsc = !sortcl->reverse_sort;
- wc->inRangeNullsFirst = sortcl->nulls_first;
- }
-
- /* Per spec, GROUPS mode requires an ORDER BY clause */
- if (wc->frameOptions & FRAMEOPTION_GROUPS)
- {
- if (wc->orderClause == NIL)
- ereport(ERROR,
- (errcode(ERRCODE_WINDOWING_ERROR),
- errmsg("GROUPS mode requires an ORDER BY clause"),
- parser_errposition(pstate, windef->location)));
- }
-
- /* Process frame offset expressions */
- wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
- rangeopfamily, rangeopcintype,
- &wc->startInRangeFunc,
- windef->startOffset);
- wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
- rangeopfamily, rangeopcintype,
- &wc->endInRangeFunc,
- windef->endOffset);
- wc->winref = winref;
-
- result = lappend(result, wc);
- }
+ /*
+ * The QUALIFY clause is transformed in analyze.c and passed here.
+ * We might attach it to WindowClause nodes later if needed, but for now
+ * we rely on Query->qualifyQual.
+ */
- return result;
+ foreach(lc, windowdefs)
+ {
+ WindowDef *windef = (WindowDef *) lfirst(lc);
+ WindowClause *refwc = NULL;
+ List *partitionClause;
+ List *orderClause;
+ Oid rangeopfamily = InvalidOid;
+ Oid rangeopcintype = InvalidOid;
+ WindowClause *wc;
+
+ winref++;
+
+ /*
+ * Check for duplicate window names.
+ */
+ if (windef->name &&
+ findWindowClause(result, windef->name) != NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("window \"%s\" is already defined", windef->name),
+ parser_errposition(pstate, windef->location)));
+
+ /*
+ * If it references a previous window, look that up.
+ */
+ if (windef->refname)
+ {
+ refwc = findWindowClause(result, windef->refname);
+ if (refwc == NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("window \"%s\" does not exist",
+ windef->refname),
+ parser_errposition(pstate, windef->location)));
+ }
+
+ /*
+ * Transform PARTITION and ORDER specs, if any.
+ */
+ orderClause = transformSortClause(pstate,
+ windef->orderClause,
+ targetlist,
+ EXPR_KIND_WINDOW_ORDER,
+ true /* force SQL99 rules */ );
+ partitionClause = transformGroupClause(pstate,
+ windef->partitionClause,
+ false /* not GROUP BY ALL */ ,
+ NULL,
+ targetlist,
+ orderClause,
+ EXPR_KIND_WINDOW_PARTITION,
+ true /* force SQL99 rules */ );
+
+ /*
+ * And prepare the new WindowClause.
+ */
+ wc = makeNode(WindowClause);
+ wc->name = windef->name;
+ wc->refname = windef->refname;
+
+ /*
+ * ADDED: Attach the transformed QUALIFY clause.
+ * Note: This attaches the same qual to every window definition.
+ * The planner must be smart enough to apply it only once globally
+ * or at the top-level window node.
+ */
+ wc->qualifyQual = transformedQualify;
+
+ /*
+ * Per spec, a windowdef that references a previous one copies ...
+ */
+ if (refwc)
+ {
+ if (partitionClause)
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("cannot override PARTITION BY clause of window \"%s\"",
+ windef->refname),
+ parser_errposition(pstate, windef->location)));
+ wc->partitionClause = copyObject(refwc->partitionClause);
+ }
+ else
+ wc->partitionClause = partitionClause;
+
+ if (refwc)
+ {
+ if (orderClause && refwc->orderClause)
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("cannot override ORDER BY clause of window \"%s\"",
+ windef->refname),
+ parser_errposition(pstate, windef->location)));
+ if (orderClause)
+ {
+ wc->orderClause = orderClause;
+ wc->copiedOrder = false;
+ }
+ else
+ {
+ wc->orderClause = copyObject(refwc->orderClause);
+ wc->copiedOrder = true;
+ }
+ }
+ else
+ {
+ wc->orderClause = orderClause;
+ wc->copiedOrder = false;
+ }
+
+ if (refwc && refwc->frameOptions != FRAMEOPTION_DEFAULTS)
+ {
+ if (windef->name ||
+ orderClause || windef->frameOptions != FRAMEOPTION_DEFAULTS)
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("cannot copy window \"%s\" because it has a frame clause",
+ windef->refname),
+ parser_errposition(pstate, windef->location)));
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("cannot copy window \"%s\" because it has a frame clause",
+ windef->refname),
+ errhint("Omit the parentheses in this OVER clause."),
+ parser_errposition(pstate, windef->location)));
+ }
+ wc->frameOptions = windef->frameOptions;
+
+ /*
+ * RANGE offset PRECEDING/FOLLOWING checks
+ */
+ if ((wc->frameOptions & FRAMEOPTION_RANGE) &&
+ (wc->frameOptions & (FRAMEOPTION_START_OFFSET |
+ FRAMEOPTION_END_OFFSET)))
+ {
+ SortGroupClause *sortcl;
+ Node *sortkey;
+ CompareType rangecmptype;
+
+ if (list_length(wc->orderClause) != 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column"),
+ parser_errposition(pstate, windef->location)));
+ sortcl = linitial_node(SortGroupClause, wc->orderClause);
+ sortkey = get_sortgroupclause_expr(sortcl, *targetlist);
+
+ if (!get_ordering_op_properties(sortcl->sortop,
+ &rangeopfamily,
+ &rangeopcintype,
+ &rangecmptype))
+ elog(ERROR, "operator %u is not a valid ordering operator",
+ sortcl->sortop);
+
+ wc->inRangeColl = exprCollation(sortkey);
+ wc->inRangeAsc = !sortcl->reverse_sort;
+ wc->inRangeNullsFirst = sortcl->nulls_first;
+ }
+
+ /* Per spec, GROUPS mode requires an ORDER BY clause */
+ if (wc->frameOptions & FRAMEOPTION_GROUPS)
+ {
+ if (wc->orderClause == NIL)
+ ereport(ERROR,
+ (errcode(ERRCODE_WINDOWING_ERROR),
+ errmsg("GROUPS mode requires an ORDER BY clause"),
+ parser_errposition(pstate, windef->location)));
+ }
+
+ /* Process frame offset expressions */
+ wc->startOffset = transformFrameOffset(pstate, wc->frameOptions,
+ rangeopfamily, rangeopcintype,
+ &wc->startInRangeFunc,
+ windef->startOffset);
+ wc->endOffset = transformFrameOffset(pstate, wc->frameOptions,
+ rangeopfamily, rangeopcintype,
+ &wc->endInRangeFunc,
+ windef->endOffset);
+ wc->winref = winref;
+
+ result = lappend(result, wc);
+ }
+
+ return result;
}
+
/*
* transformDistinctClause -
* transform a DISTINCT clause
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 44fd1385f8c..4ca07f3571a 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -542,6 +542,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_WHERE:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_FILTER:
case EXPR_KIND_WINDOW_PARTITION:
case EXPR_KIND_WINDOW_ORDER:
@@ -847,6 +848,37 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
parser_errposition(pstate, cref->location)));
}
+ /*
+ * If we haven't found a column, and we are in a QUALIFY clause,
+ * try to resolve the name as an output column alias.
+ */
+ if (node == NULL &&
+ list_length(cref->fields) == 1 &&
+ pstate->p_expr_kind == EXPR_KIND_QUALIFY)
+ {
+ ListCell *lc;
+ Node *match = NULL;
+
+ foreach(lc, pstate->p_targetList)
+ {
+ TargetEntry *tle = (TargetEntry *) lfirst(lc);
+
+ if (tle->resname != NULL && strcmp(tle->resname, colname) == 0)
+ {
+ if (match != NULL)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_AMBIGUOUS_COLUMN),
+ errmsg("column reference \"%s\" is ambiguous",
+ colname),
+ parser_errposition(pstate, cref->location)));
+ }
+ match = (Node *) copyObject(tle->expr);
+ }
+ }
+ node = match;
+ }
+
/*
* Throw error if no translation found.
*/
@@ -1797,6 +1829,7 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_WHERE:
case EXPR_KIND_POLICY:
case EXPR_KIND_HAVING:
+ case EXPR_KIND_QUALIFY:
case EXPR_KIND_FILTER:
case EXPR_KIND_WINDOW_PARTITION:
case EXPR_KIND_WINDOW_ORDER:
@@ -3153,6 +3186,8 @@ ParseExprKindName(ParseExprKind exprKind)
return "POLICY";
case EXPR_KIND_HAVING:
return "HAVING";
+ case EXPR_KIND_QUALIFY:
+ return "QUALIFY";
case EXPR_KIND_FILTER:
return "FILTER";
case EXPR_KIND_WINDOW_PARTITION:
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 778d69c6f3c..6f94bf5c342 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -2686,7 +2686,10 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
err = _("set-returning functions are not allowed in policy expressions");
break;
case EXPR_KIND_HAVING:
- errkind = true;
+ /* okay */
+ break;
+ case EXPR_KIND_QUALIFY:
+ err = _("set-returning functions are not allowed in QUALIFY");
break;
case EXPR_KIND_FILTER:
errkind = true;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index d14294a4ece..2b5b1a77a4d 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -116,148 +116,152 @@ typedef uint64 AclMode; /* a bitmask of privilege bits */
*/
typedef struct Query
{
- NodeTag type;
-
- CmdType commandType; /* select|insert|update|delete|merge|utility */
-
- /* where did I come from? */
- QuerySource querySource pg_node_attr(query_jumble_ignore);
-
- /*
- * query identifier (can be set by plugins); ignored for equal, as it
- * might not be set; also not stored. This is the result of the query
- * jumble, hence ignored.
- *
- * We store this as a signed value as this is the form it's displayed to
- * users in places such as EXPLAIN and pg_stat_statements. Primarily this
- * is done due to lack of an SQL type to represent the full range of
- * uint64.
- */
- int64 queryId pg_node_attr(equal_ignore, query_jumble_ignore, read_write_ignore, read_as(0));
-
- /* do I set the command result tag? */
- bool canSetTag pg_node_attr(query_jumble_ignore);
-
- Node *utilityStmt; /* non-null if commandType == CMD_UTILITY */
-
- /*
- * rtable index of target relation for INSERT/UPDATE/DELETE/MERGE; 0 for
- * SELECT. This is ignored in the query jumble as unrelated to the
- * compilation of the query ID.
- */
- int resultRelation pg_node_attr(query_jumble_ignore);
-
- /* has aggregates in tlist or havingQual */
- bool hasAggs pg_node_attr(query_jumble_ignore);
- /* has window functions in tlist */
- bool hasWindowFuncs pg_node_attr(query_jumble_ignore);
- /* has set-returning functions in tlist */
- bool hasTargetSRFs pg_node_attr(query_jumble_ignore);
- /* has subquery SubLink */
- bool hasSubLinks pg_node_attr(query_jumble_ignore);
- /* distinctClause is from DISTINCT ON */
- bool hasDistinctOn pg_node_attr(query_jumble_ignore);
- /* WITH RECURSIVE was specified */
- bool hasRecursive pg_node_attr(query_jumble_ignore);
- /* has INSERT/UPDATE/DELETE/MERGE in WITH */
- bool hasModifyingCTE pg_node_attr(query_jumble_ignore);
- /* FOR [KEY] UPDATE/SHARE was specified */
- bool hasForUpdate pg_node_attr(query_jumble_ignore);
- /* rewriter has applied some RLS policy */
- bool hasRowSecurity pg_node_attr(query_jumble_ignore);
- /* parser has added an RTE_GROUP RTE */
- bool hasGroupRTE pg_node_attr(query_jumble_ignore);
- /* is a RETURN statement */
- bool isReturn pg_node_attr(query_jumble_ignore);
-
- List *cteList; /* WITH list (of CommonTableExpr's) */
-
- List *rtable; /* list of range table entries */
-
- /*
- * list of RTEPermissionInfo nodes for the rtable entries having
- * perminfoindex > 0
- */
- List *rteperminfos pg_node_attr(query_jumble_ignore);
- FromExpr *jointree; /* table join tree (FROM and WHERE clauses);
- * also USING clause for MERGE */
-
- List *mergeActionList; /* list of actions for MERGE (only) */
-
- /*
- * rtable index of target relation for MERGE to pull data. Initially, this
- * is the same as resultRelation, but after query rewriting, if the target
- * relation is a trigger-updatable view, this is the index of the expanded
- * view subquery, whereas resultRelation is the index of the target view.
- */
- int mergeTargetRelation pg_node_attr(query_jumble_ignore);
-
- /* join condition between source and target for MERGE */
- Node *mergeJoinCondition;
-
- List *targetList; /* target list (of TargetEntry) */
-
- /* OVERRIDING clause */
- OverridingKind override pg_node_attr(query_jumble_ignore);
-
- OnConflictExpr *onConflict; /* ON CONFLICT DO [NOTHING | UPDATE] */
-
- /*
- * The following three fields describe the contents of the RETURNING list
- * for INSERT/UPDATE/DELETE/MERGE. returningOldAlias and returningNewAlias
- * are the alias names for OLD and NEW, which may be user-supplied values,
- * the defaults "old" and "new", or NULL (if the default "old"/"new" is
- * already in use as the alias for some other relation).
- */
- char *returningOldAlias pg_node_attr(query_jumble_ignore);
- char *returningNewAlias pg_node_attr(query_jumble_ignore);
- List *returningList; /* return-values list (of TargetEntry) */
-
- List *groupClause; /* a list of SortGroupClause's */
- bool groupDistinct; /* was GROUP BY DISTINCT used? */
- bool groupByAll; /* was GROUP BY ALL used? */
-
- List *groupingSets; /* a list of GroupingSet's if present */
-
- Node *havingQual; /* qualifications applied to groups */
-
- List *windowClause; /* a list of WindowClause's */
-
- List *distinctClause; /* a list of SortGroupClause's */
-
- List *sortClause; /* a list of SortGroupClause's */
-
- Node *limitOffset; /* # of result tuples to skip (int8 expr) */
- Node *limitCount; /* # of result tuples to return (int8 expr) */
- LimitOption limitOption; /* limit type */
-
- List *rowMarks; /* a list of RowMarkClause's */
-
- Node *setOperations; /* set-operation tree if this is top level of
- * a UNION/INTERSECT/EXCEPT query */
-
- /*
- * A list of pg_constraint OIDs that the query depends on to be
- * semantically valid
- */
- List *constraintDeps pg_node_attr(query_jumble_ignore);
-
- /* a list of WithCheckOption's (added during rewrite) */
- List *withCheckOptions pg_node_attr(query_jumble_ignore);
-
- /*
- * The following two fields identify the portion of the source text string
- * containing this query. They are typically only populated in top-level
- * Queries, not in sub-queries. When not set, they might both be zero, or
- * both be -1 meaning "unknown".
- */
- /* start location, or -1 if unknown */
- ParseLoc stmt_location;
- /* length in bytes; 0 means "rest of string" */
- ParseLoc stmt_len pg_node_attr(query_jumble_ignore);
+ NodeTag type;
+
+ CmdType commandType; /* select|insert|update|delete|merge|utility */
+
+ /* where did I come from? */
+ QuerySource querySource pg_node_attr(query_jumble_ignore);
+
+ /*
+ * query identifier (can be set by plugins); ignored for equal, as it
+ * might not be set; also not stored. This is the result of the query
+ * jumble, hence ignored.
+ *
+ * We store this as a signed value as this is the form it's displayed to
+ * users in places such as EXPLAIN and pg_stat_statements. Primarily this
+ * is done due to lack of an SQL type to represent the full range of
+ * uint64.
+ */
+ int64 queryId pg_node_attr(equal_ignore, query_jumble_ignore, read_write_ignore, read_as(0));
+
+ /* do I set the command result tag? */
+ bool canSetTag pg_node_attr(query_jumble_ignore);
+
+ Node *utilityStmt; /* non-null if commandType == CMD_UTILITY */
+
+ /*
+ * rtable index of target relation for INSERT/UPDATE/DELETE/MERGE; 0 for
+ * SELECT. This is ignored in the query jumble as unrelated to the
+ * compilation of the query ID.
+ */
+ int resultRelation pg_node_attr(query_jumble_ignore);
+
+ /* has aggregates in tlist or havingQual */
+ bool hasAggs pg_node_attr(query_jumble_ignore);
+ /* has window functions in tlist */
+ bool hasWindowFuncs pg_node_attr(query_jumble_ignore);
+ /* has set-returning functions in tlist */
+ bool hasTargetSRFs pg_node_attr(query_jumble_ignore);
+ /* has subquery SubLink */
+ bool hasSubLinks pg_node_attr(query_jumble_ignore);
+ /* distinctClause is from DISTINCT ON */
+ bool hasDistinctOn pg_node_attr(query_jumble_ignore);
+ /* WITH RECURSIVE was specified */
+ bool hasRecursive pg_node_attr(query_jumble_ignore);
+ /* has INSERT/UPDATE/DELETE/MERGE in WITH */
+ bool hasModifyingCTE pg_node_attr(query_jumble_ignore);
+ /* FOR [KEY] UPDATE/SHARE was specified */
+ bool hasForUpdate pg_node_attr(query_jumble_ignore);
+ /* rewriter has applied some RLS policy */
+ bool hasRowSecurity pg_node_attr(query_jumble_ignore);
+ /* parser has added an RTE_GROUP RTE */
+ bool hasGroupRTE pg_node_attr(query_jumble_ignore);
+ /* is a RETURN statement */
+ bool isReturn pg_node_attr(query_jumble_ignore);
+
+ List *cteList; /* WITH list (of CommonTableExpr's) */
+
+ List *rtable; /* list of range table entries */
+
+ /*
+ * list of RTEPermissionInfo nodes for the rtable entries having
+ * perminfoindex > 0
+ */
+ List *rteperminfos pg_node_attr(query_jumble_ignore);
+ FromExpr *jointree; /* table join tree (FROM and WHERE clauses);
+ * also USING clause for MERGE */
+
+ List *mergeActionList; /* list of actions for MERGE (only) */
+
+ /*
+ * rtable index of target relation for MERGE to pull data. Initially, this
+ * is the same as resultRelation, but after query rewriting, if the target
+ * relation is a trigger-updatable view, this is the index of the expanded
+ * view subquery, whereas resultRelation is the index of the target view.
+ */
+ int mergeTargetRelation pg_node_attr(query_jumble_ignore);
+
+ /* join condition between source and target for MERGE */
+ Node *mergeJoinCondition;
+
+ List *targetList; /* target list (of TargetEntry) */
+
+ /* OVERRIDING clause */
+ OverridingKind override pg_node_attr(query_jumble_ignore);
+
+ OnConflictExpr *onConflict; /* ON CONFLICT DO [NOTHING | UPDATE] */
+
+ /*
+ * The following three fields describe the contents of the RETURNING list
+ * for INSERT/UPDATE/DELETE/MERGE. returningOldAlias and returningNewAlias
+ * are the alias names for OLD and NEW, which may be user-supplied values,
+ * the defaults "old" and "new", or NULL (if the default "old"/"new" is
+ * already in use as the alias for some other relation).
+ */
+ char *returningOldAlias pg_node_attr(query_jumble_ignore);
+ char *returningNewAlias pg_node_attr(query_jumble_ignore);
+ List *returningList; /* return-values list (of TargetEntry) */
+
+ List *groupClause; /* a list of SortGroupClause's */
+ bool groupDistinct; /* was GROUP BY DISTINCT used? */
+ bool groupByAll; /* was GROUP BY ALL used? */
+
+ List *groupingSets; /* a list of GroupingSet's if present */
+
+ Node *havingQual; /* qualifications applied to groups */
+
+ /* ADDED: QUALIFY clause */
+ Node *qualifyQual; /* qualifications applied to window functions */
+
+ List *windowClause; /* a list of WindowClause's */
+
+ List *distinctClause; /* a list of SortGroupClause's */
+
+ List *sortClause; /* a list of SortGroupClause's */
+
+ Node *limitOffset; /* # of result tuples to skip (int8 expr) */
+ Node *limitCount; /* # of result tuples to return (int8 expr) */
+ LimitOption limitOption; /* limit type */
+
+ List *rowMarks; /* a list of RowMarkClause's */
+
+ Node *setOperations; /* set-operation tree if this is top level of
+ * a UNION/INTERSECT/EXCEPT query */
+
+ /*
+ * A list of pg_constraint OIDs that the query depends on to be
+ * semantically valid
+ */
+ List *constraintDeps pg_node_attr(query_jumble_ignore);
+
+ /* a list of WithCheckOption's (added during rewrite) */
+ List *withCheckOptions pg_node_attr(query_jumble_ignore);
+
+ /*
+ * The following two fields identify the portion of the source text string
+ * containing this query. They are typically only populated in top-level
+ * Queries, not in sub-queries. When not set, they might both be zero, or
+ * both be -1 meaning "unknown".
+ */
+ /* start location, or -1 if unknown */
+ ParseLoc stmt_location;
+ /* length in bytes; 0 means "rest of string" */
+ ParseLoc stmt_len pg_node_attr(query_jumble_ignore);
} Query;
+
/****************************************************************************
* Supporting data structures for Parse Trees
*
@@ -596,6 +600,10 @@ typedef struct WindowDef
int frameOptions; /* frame_clause options, see below */
Node *startOffset; /* expression for starting bound, if any */
Node *endOffset; /* expression for ending bound, if any */
+
+ /* QUALIFY clause */
+ Node *qualifyQual;
+
ParseLoc location; /* parse location, or -1 if none/unknown */
} WindowDef;
@@ -1222,6 +1230,7 @@ typedef struct RangeTblEntry
/*
* Fields valid for a CTE RTE (else NULL/zero):
+ *
*/
/* name of the WITH list item */
char *ctename;
@@ -1566,32 +1575,37 @@ typedef struct GroupingSet
*/
typedef struct WindowClause
{
- NodeTag type;
- /* window name (NULL in an OVER clause) */
- char *name pg_node_attr(query_jumble_ignore);
- /* referenced window name, if any */
- char *refname pg_node_attr(query_jumble_ignore);
- List *partitionClause; /* PARTITION BY list */
- /* ORDER BY list */
- List *orderClause;
- int frameOptions; /* frame_clause options, see WindowDef */
- Node *startOffset; /* expression for starting bound, if any */
- Node *endOffset; /* expression for ending bound, if any */
- /* in_range function for startOffset */
- Oid startInRangeFunc pg_node_attr(query_jumble_ignore);
- /* in_range function for endOffset */
- Oid endInRangeFunc pg_node_attr(query_jumble_ignore);
- /* collation for in_range tests */
- Oid inRangeColl pg_node_attr(query_jumble_ignore);
- /* use ASC sort order for in_range tests? */
- bool inRangeAsc pg_node_attr(query_jumble_ignore);
- /* nulls sort first for in_range tests? */
- bool inRangeNullsFirst pg_node_attr(query_jumble_ignore);
- Index winref; /* ID referenced by window functions */
- /* did we copy orderClause from refname? */
- bool copiedOrder pg_node_attr(query_jumble_ignore);
+ NodeTag type;
+ /* window name (NULL in an OVER clause) */
+ char *name pg_node_attr(query_jumble_ignore);
+ /* referenced window name, if any */
+ char *refname pg_node_attr(query_jumble_ignore);
+ List *partitionClause; /* PARTITION BY list */
+ /* ORDER BY list */
+ List *orderClause;
+ int frameOptions; /* frame_clause options, see WindowDef */
+ Node *startOffset; /* expression for starting bound, if any */
+ Node *endOffset; /* expression for ending bound, if any */
+
+ /* ADDED: QUALIFY clause */
+ Node *qualifyQual; /* qualifications applied to window functions */
+
+ /* in_range function for startOffset */
+ Oid startInRangeFunc pg_node_attr(query_jumble_ignore);
+ /* in_range function for endOffset */
+ Oid endInRangeFunc pg_node_attr(query_jumble_ignore);
+ /* collation for in_range tests */
+ Oid inRangeColl pg_node_attr(query_jumble_ignore);
+ /* use ASC sort order for in_range tests? */
+ bool inRangeAsc pg_node_attr(query_jumble_ignore);
+ /* nulls sort first for in_range tests? */
+ bool inRangeNullsFirst pg_node_attr(query_jumble_ignore);
+ Index winref; /* ID referenced by window functions */
+ /* did we copy orderClause from refname? */
+ bool copiedOrder pg_node_attr(query_jumble_ignore);
} WindowClause;
+
/*
* RowMarkClause -
* parser output representation of FOR [KEY] UPDATE/SHARE clauses
@@ -2181,55 +2195,60 @@ typedef enum SetOperation
typedef struct SelectStmt
{
- NodeTag type;
-
- /*
- * These fields are used only in "leaf" SelectStmts.
- */
- List *distinctClause; /* NULL, list of DISTINCT ON exprs, or
- * lcons(NIL,NIL) for all (SELECT DISTINCT) */
- IntoClause *intoClause; /* target for SELECT INTO */
- List *targetList; /* the target list (of ResTarget) */
- List *fromClause; /* the FROM clause */
- Node *whereClause; /* WHERE qualification */
- List *groupClause; /* GROUP BY clauses */
- bool groupDistinct; /* Is this GROUP BY DISTINCT? */
- bool groupByAll; /* Is this GROUP BY ALL? */
- Node *havingClause; /* HAVING conditional-expression */
- List *windowClause; /* WINDOW window_name AS (...), ... */
-
- /*
- * In a "leaf" node representing a VALUES list, the above fields are all
- * null, and instead this field is set. Note that the elements of the
- * sublists are just expressions, without ResTarget decoration. Also note
- * that a list element can be DEFAULT (represented as a SetToDefault
- * node), regardless of the context of the VALUES list. It's up to parse
- * analysis to reject that where not valid.
- */
- List *valuesLists; /* untransformed list of expression lists */
-
- /*
- * These fields are used in both "leaf" SelectStmts and upper-level
- * SelectStmts.
- */
- List *sortClause; /* sort clause (a list of SortBy's) */
- Node *limitOffset; /* # of result tuples to skip */
- Node *limitCount; /* # of result tuples to return */
- LimitOption limitOption; /* limit type */
- List *lockingClause; /* FOR UPDATE (list of LockingClause's) */
- WithClause *withClause; /* WITH clause */
-
- /*
- * These fields are used only in upper-level SelectStmts.
- */
- SetOperation op; /* type of set op */
- bool all; /* ALL specified? */
- struct SelectStmt *larg; /* left child */
- struct SelectStmt *rarg; /* right child */
- /* Eventually add fields for CORRESPONDING spec here */
+ NodeTag type;
+
+ /*
+ * These fields are used only in "leaf" SelectStmts.
+ */
+ List *distinctClause; /* NULL, list of DISTINCT ON exprs, or
+ * lcons(NIL,NIL) for all (SELECT DISTINCT) */
+ IntoClause *intoClause; /* target for SELECT INTO */
+ List *targetList; /* the target list (of ResTarget) */
+ List *fromClause; /* the FROM clause */
+ Node *whereClause; /* WHERE qualification */
+
+ /* ADDED: QUALIFY clause */
+ Node *qualifyClause; /* QUALIFY qualification */
+
+ List *groupClause; /* GROUP BY clauses */
+ bool groupDistinct; /* Is this GROUP BY DISTINCT? */
+ bool groupByAll; /* Is this GROUP BY ALL? */
+ Node *havingClause; /* HAVING conditional-expression */
+ List *windowClause; /* WINDOW window_name AS (...), ... */
+
+ /*
+ * In a "leaf" node representing a VALUES list, the above fields are all
+ * null, and instead this field is set. Note that the elements of the
+ * sublists are just expressions, without ResTarget decoration. Also note
+ * that a list element can be DEFAULT (represented as a SetToDefault
+ * node), regardless of the context of the VALUES list. It's up to parse
+ * analysis to reject that where not valid.
+ */
+ List *valuesLists; /* untransformed list of expression lists */
+
+ /*
+ * These fields are used in both "leaf" SelectStmts and upper-level
+ * SelectStmts.
+ */
+ List *sortClause; /* sort clause (a list of SortBy's) */
+ Node *limitOffset; /* # of result tuples to skip */
+ Node *limitCount; /* # of result tuples to return */
+ LimitOption limitOption; /* limit type */
+ List *lockingClause; /* FOR UPDATE (list of LockingClause's) */
+ WithClause *withClause; /* WITH clause */
+
+ /*
+ * These fields are used only in upper-level SelectStmts.
+ */
+ SetOperation op; /* type of set op */
+ bool all; /* ALL specified? */
+ struct SelectStmt *larg; /* left child */
+ struct SelectStmt *rarg; /* right child */
+ /* Eventually add fields for CORRESPONDING spec here */
} SelectStmt;
+
/* ----------------------
* Set Operation node for post-analysis query trees
*
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 5d4fe27ef96..3c493dc996f 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -361,6 +361,7 @@ PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("qualify", QUALIFY, RESERVED_KEYWORD, AS_LABEL)
PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("quotes", QUOTES, UNRESERVED_KEYWORD, BARE_LABEL)
PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/include/parser/parse_clause.h b/src/include/parser/parse_clause.h
index ede3903d1dd..97b78d095a5 100644
--- a/src/include/parser/parse_clause.h
+++ b/src/include/parser/parse_clause.h
@@ -36,7 +36,8 @@ extern List *transformSortClause(ParseState *pstate, List *orderlist,
extern List *transformWindowDefinitions(ParseState *pstate,
List *windowdefs,
- List **targetlist);
+ List **targetlist,
+ Node *qualifyClause);
extern List *transformDistinctClause(ParseState *pstate,
List **targetlist, List *sortClause, bool is_agg);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f7d07c84542..05f0f17ba3d 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -45,6 +45,7 @@ typedef enum ParseExprKind
EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
EXPR_KIND_WHERE, /* WHERE */
EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_QUALIFY, /* QUALIFY */
EXPR_KIND_FILTER, /* FILTER */
EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
@@ -231,6 +232,8 @@ struct ParseState
Node *p_last_srf; /* most recent set-returning func/op found */
+ List *p_targetList; /* target list (of TargetEntry) */
+
/*
* Optional hook functions for parser callbacks. These are null unless
* set up by the caller of make_parsestate.
diff --git a/src/test/regress/expected/qualify.out b/src/test/regress/expected/qualify.out
new file mode 100644
index 00000000000..a742a726f21
--- /dev/null
+++ b/src/test/regress/expected/qualify.out
@@ -0,0 +1,147 @@
+--
+-- QUALIFY clause tests
+--
+CREATE TEMP TABLE qualify_test (
+ id int,
+ val int,
+ grp int
+);
+INSERT INTO qualify_test VALUES
+ (1, 10, 1),
+ (2, 20, 1),
+ (3, 30, 1),
+ (4, 10, 2),
+ (5, 40, 2),
+ (6, 50, 2);
+-- Simple QUALIFY
+SELECT id, val, grp, rank() OVER (PARTITION BY grp ORDER BY val) as r
+FROM qualify_test
+QUALIFY rank() OVER (PARTITION BY grp ORDER BY val) > 1;
+ id | val | grp | r
+----+-----+-----+---
+ 2 | 20 | 1 | 2
+ 3 | 30 | 1 | 3
+ 5 | 40 | 2 | 2
+ 6 | 50 | 2 | 3
+(4 rows)
+
+-- QUALIFY with alias (not supported directly in standard SQL usually, but Postgres allows aliases in GROUP BY/HAVING sometimes.
+-- In QUALIFY, we might need to repeat the expression or use a window alias)
+-- Postgres doesn't support column aliases in HAVING usually.
+-- Let's try repeating the expression first.
+SELECT id, val, grp
+FROM qualify_test
+QUALIFY rank() OVER (PARTITION BY grp ORDER BY val) = 1;
+ id | val | grp
+----+-----+-----
+ 1 | 10 | 1
+ 2 | 20 | 1
+ 3 | 30 | 1
+ 4 | 10 | 2
+ 5 | 40 | 2
+ 6 | 50 | 2
+(6 rows)
+
+-- QUALIFY with WHERE
+SELECT id, val, grp
+FROM qualify_test
+WHERE val > 10
+QUALIFY count(*) OVER (PARTITION BY grp) > 1;
+ id | val | grp
+----+-----+-----
+ 2 | 20 | 1
+ 3 | 30 | 1
+ 5 | 40 | 2
+ 6 | 50 | 2
+(4 rows)
+
+-- QUALIFY with GROUP BY and HAVING
+SELECT grp, sum(val) as sum_val
+FROM qualify_test
+GROUP BY grp
+HAVING sum(val) > 20
+QUALIFY rank() OVER (ORDER BY sum(val) DESC) = 1;
+ grp | sum_val
+-----+---------
+ 2 | 100
+ 1 | 60
+(2 rows)
+
+-- QUALIFY with Window Alias
+SELECT id, val, grp, rank() OVER w as r
+FROM qualify_test
+WINDOW w AS (PARTITION BY grp ORDER BY val)
+QUALIFY rank() OVER w > 1;
+ id | val | grp | r
+----+-----+-----+---
+ 2 | 20 | 1 | 2
+ 3 | 30 | 1 | 3
+ 5 | 40 | 2 | 2
+ 6 | 50 | 2 | 3
+(4 rows)
+
+-- QUALIFY with aggregates allowed (as arguments to window functions or if windowed)
+-- But plain aggregates are NOT allowed in QUALIFY unless they are part of a window function or the query is grouped.
+-- Actually, QUALIFY is evaluated after window functions.
+-- If the query is grouped, aggregates are evaluated before window functions.
+-- So aggregates in QUALIFY are allowed if they are valid in the SELECT list.
+-- Grouped query with aggregate in QUALIFY
+SELECT grp, sum(val)
+FROM qualify_test
+GROUP BY grp
+QUALIFY sum(val) > 50; -- This acts like HAVING, but technically allowed if we consider it a filter after windowing (which is identity here)
+ grp | sum
+-----+-----
+ 2 | 100
+ 1 | 60
+(2 rows)
+
+-- Window function over aggregate
+SELECT grp, sum(val), rank() OVER (ORDER BY sum(val))
+FROM qualify_test
+GROUP BY grp
+QUALIFY rank() OVER (ORDER BY sum(val)) > 1;
+ grp | sum | rank
+-----+-----+------
+ 2 | 100 | 2
+(1 row)
+
+-- Negative tests
+-- Set-returning function in QUALIFY (should fail)
+SELECT id, val
+FROM qualify_test
+QUALIFY generate_series(1,3) > 1;
+ERROR: set-returning functions are not allowed in QUALIFY
+LINE 3: QUALIFY generate_series(1,3) > 1;
+ ^
+-- Plain aggregate in QUALIFY without grouping (should fail like in WHERE? No, like in HAVING?)
+-- If query is not grouped, aggregate in QUALIFY implies grouping?
+-- No, QUALIFY is after windowing.
+-- If I say SELECT * FROM t QUALIFY sum(val) > 10
+-- This should probably fail if not grouped, or imply grouping?
+-- In Postgres, HAVING sum(val) > 10 implies grouping if no GROUP BY.
+-- But QUALIFY is specifically for window functions.
+-- If I use a plain aggregate, it might be ambiguous.
+-- Snowflake allows it (equivalent to HAVING).
+-- Let's see what my implementation does.
+-- I added EXPR_KIND_QUALIFY to parse_agg.c to allow aggregates.
+-- But in parse_func.c I disallowed SRFs.
+-- Test QUALIFY with output column alias (should work now)
+SELECT id, val, grp, rank() OVER (PARTITION BY grp ORDER BY val) as r
+FROM qualify_test
+QUALIFY r = 1;
+ id | val | grp | r
+----+-----+-----+---
+ 1 | 10 | 1 | 1
+ 4 | 10 | 2 | 1
+(2 rows)
+
+-- Test ambiguous alias in QUALIFY
+SELECT 1 as x, 2 as x
+FROM qualify_test
+QUALIFY x = 1;
+ERROR: column reference "x" is ambiguous
+LINE 3: QUALIFY x = 1;
+ ^
+-- Clean up
+DROP TABLE qualify_test;
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index cc6d799bcea..7b5a9b8e35c 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -102,7 +102,7 @@ test: publication subscription
# Another group of parallel tests
# select_views depends on create_view
# ----------
-test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite
+test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass stats_rewrite qualify
# ----------
# Another group of parallel tests (JSON related)
diff --git a/src/test/regress/sql/qualify.sql b/src/test/regress/sql/qualify.sql
new file mode 100644
index 00000000000..5ec22c1fdf3
--- /dev/null
+++ b/src/test/regress/sql/qualify.sql
@@ -0,0 +1,101 @@
+--
+-- QUALIFY clause tests
+--
+
+CREATE TEMP TABLE qualify_test (
+ id int,
+ val int,
+ grp int
+);
+
+INSERT INTO qualify_test VALUES
+ (1, 10, 1),
+ (2, 20, 1),
+ (3, 30, 1),
+ (4, 10, 2),
+ (5, 40, 2),
+ (6, 50, 2);
+
+-- Simple QUALIFY
+SELECT id, val, grp, rank() OVER (PARTITION BY grp ORDER BY val) as r
+FROM qualify_test
+QUALIFY rank() OVER (PARTITION BY grp ORDER BY val) > 1;
+
+-- QUALIFY with alias (not supported directly in standard SQL usually, but Postgres allows aliases in GROUP BY/HAVING sometimes.
+-- In QUALIFY, we might need to repeat the expression or use a window alias)
+-- Postgres doesn't support column aliases in HAVING usually.
+-- Let's try repeating the expression first.
+
+SELECT id, val, grp
+FROM qualify_test
+QUALIFY rank() OVER (PARTITION BY grp ORDER BY val) = 1;
+
+-- QUALIFY with WHERE
+SELECT id, val, grp
+FROM qualify_test
+WHERE val > 10
+QUALIFY count(*) OVER (PARTITION BY grp) > 1;
+
+-- QUALIFY with GROUP BY and HAVING
+SELECT grp, sum(val) as sum_val
+FROM qualify_test
+GROUP BY grp
+HAVING sum(val) > 20
+QUALIFY rank() OVER (ORDER BY sum(val) DESC) = 1;
+
+-- QUALIFY with Window Alias
+SELECT id, val, grp, rank() OVER w as r
+FROM qualify_test
+WINDOW w AS (PARTITION BY grp ORDER BY val)
+QUALIFY rank() OVER w > 1;
+
+-- QUALIFY with aggregates allowed (as arguments to window functions or if windowed)
+-- But plain aggregates are NOT allowed in QUALIFY unless they are part of a window function or the query is grouped.
+-- Actually, QUALIFY is evaluated after window functions.
+-- If the query is grouped, aggregates are evaluated before window functions.
+-- So aggregates in QUALIFY are allowed if they are valid in the SELECT list.
+
+-- Grouped query with aggregate in QUALIFY
+SELECT grp, sum(val)
+FROM qualify_test
+GROUP BY grp
+QUALIFY sum(val) > 50; -- This acts like HAVING, but technically allowed if we consider it a filter after windowing (which is identity here)
+
+-- Window function over aggregate
+SELECT grp, sum(val), rank() OVER (ORDER BY sum(val))
+FROM qualify_test
+GROUP BY grp
+QUALIFY rank() OVER (ORDER BY sum(val)) > 1;
+
+-- Negative tests
+
+-- Set-returning function in QUALIFY (should fail)
+SELECT id, val
+FROM qualify_test
+QUALIFY generate_series(1,3) > 1;
+
+-- Plain aggregate in QUALIFY without grouping (should fail like in WHERE? No, like in HAVING?)
+-- If query is not grouped, aggregate in QUALIFY implies grouping?
+-- No, QUALIFY is after windowing.
+-- If I say SELECT * FROM t QUALIFY sum(val) > 10
+-- This should probably fail if not grouped, or imply grouping?
+-- In Postgres, HAVING sum(val) > 10 implies grouping if no GROUP BY.
+-- But QUALIFY is specifically for window functions.
+-- If I use a plain aggregate, it might be ambiguous.
+-- Snowflake allows it (equivalent to HAVING).
+-- Let's see what my implementation does.
+-- I added EXPR_KIND_QUALIFY to parse_agg.c to allow aggregates.
+-- But in parse_func.c I disallowed SRFs.
+
+-- Test QUALIFY with output column alias (should work now)
+SELECT id, val, grp, rank() OVER (PARTITION BY grp ORDER BY val) as r
+FROM qualify_test
+QUALIFY r = 1;
+
+-- Test ambiguous alias in QUALIFY
+SELECT 1 as x, 2 as x
+FROM qualify_test
+QUALIFY x = 1;
+
+-- Clean up
+DROP TABLE qualify_test;
^ permalink raw reply [nested|flat] 41+ messages in thread
end of thread, other threads:[~2026-09-24 13:06 UTC | newest]
Thread overview: 41+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-07-21 12:47 Proposal: QUALIFY clause Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 14:18 ` Mike Artz <michaeleartz@gmail.com>
2025-07-21 14:29 ` Isaac Morland <isaac.morland@gmail.com>
2025-07-21 14:41 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 20:20 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 14:47 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 17:30 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-21 18:31 ` Thom Brown <thom@linux.com>
2025-07-21 18:38 ` Marko Tiikkaja <marko@joh.to>
2025-07-21 20:26 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 20:34 ` Nico Williams <nico@cryptonector.com>
2025-07-21 20:23 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 21:29 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-21 22:11 ` Vik Fearing <vik@postgresfriends.org>
2025-07-21 22:56 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 03:19 ` Pavel Stehule <pavel.stehule@gmail.com>
2025-07-22 03:43 ` Merlin Moncure <mmoncure@gmail.com>
2025-07-22 04:08 ` Nico Williams <nico@cryptonector.com>
2025-07-22 05:02 ` Merlin Moncure <mmoncure@gmail.com>
2025-07-22 15:04 ` Nico Williams <nico@cryptonector.com>
2025-07-22 15:14 ` Nico Williams <nico@cryptonector.com>
2025-07-22 15:24 ` Vik Fearing <vik@postgresfriends.org>
2025-07-22 05:14 ` Tom Lane <tgl@sss.pgh.pa.us>
2025-07-22 15:07 ` Nico Williams <nico@cryptonector.com>
2025-07-22 15:14 ` Vik Fearing <vik@postgresfriends.org>
2025-07-22 15:26 ` Andrew Dunstan <andrew@dunslane.net>
2025-07-23 08:12 ` Álvaro Herrera <alvherre@kurilemu.de>
2025-07-22 11:55 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 18:11 ` Marcos Pegoraro <marcos@f10.com.br>
2025-07-22 18:54 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-22 21:21 ` Vik Fearing <vik@postgresfriends.org>
2025-07-22 22:32 ` David Rowley <dgrowleyml@gmail.com>
2025-07-29 00:10 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-29 00:46 ` David Rowley <dgrowleyml@gmail.com>
2025-07-29 09:48 ` Richard Guo <guofenglinux@gmail.com>
2026-06-29 14:41 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-07-14 18:23 ` Matheus Alcantara <matheusssilv97@gmail.com>
2026-09-24 13:06 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-25 12:55 ` Matheus Alcantara <matheusssilv97@gmail.com>
2025-07-25 14:50 ` Vik Fearing <vik@postgresfriends.org>
2025-12-05 12:55 Re: Proposal: QUALIFY clause Yannick Goetschel <Yannick.Goetschel@tradition.ch>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox