Skip to content

Add support for PostgreSQL's ORDER BY ... USING <operator> clause#2246

Open
LucaCappelletti94 wants to merge 3 commits intoapache:mainfrom
LucaCappelletti94:postgres-regression-2
Open

Add support for PostgreSQL's ORDER BY ... USING <operator> clause#2246
LucaCappelletti94 wants to merge 3 commits intoapache:mainfrom
LucaCappelletti94:postgres-regression-2

Conversation

@LucaCappelletti94
Copy link
Contributor

This PR adds parser and AST support for PostgreSQL USING operators in ORDER BY expressions, including:

  • top-level ORDER BY
  • aggregate argument list ORDER BY (e.g. inside aggfns(...) / string_agg(...) style clauses)

Problem

sqlparser-rs previously rejected valid PostgreSQL statements containing:

  • ORDER BY <expr> USING <operator>

with errors like:

  • Expected: ), found: using

This blocked parsing of several PostgreSQL regression-style aggregate statements.

Root Cause

parse_order_by_expr_inner only supported:

  • ASC | DESC
  • NULLS FIRST | NULLS LAST

and had no branch to parse USING <operator>.

Dialect Scope Decision

ORDER BY ... USING <operator> is intentionally enabled for PostgreSQL only.

Rationale:

  • PostgreSQL explicitly documents ORDER BY expression [ USING operator ] ... in SELECT.
  • Other dialects supported by this repository generally document ORDER BY with expression + ASC|DESC (+ null ordering), but not USING <operator>.

References:

Complete Examples

PostgreSQL: accepted

SELECT a FROM t ORDER BY a USING <;

SELECT a FROM t ORDER BY a USING OPERATOR(pg_catalog.<) NULLS LAST;

SELECT aggfns(DISTINCT a, a, c ORDER BY c USING ~<~, a)
FROM (VALUES (1,3,'foo'),(0,NULL,NULL),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
     generate_series(1,2) i;

CREATE OR REPLACE VIEW agg_view1 AS
SELECT aggfns(a,b,c ORDER BY c USING ~<~)
FROM (VALUES (1,3,'foo'),(0,NULL,NULL),(2,2,'bar'),(3,1,'baz')) v(a,b,c);

PostgreSQL: rejected (invalid syntax)

SELECT a FROM t ORDER BY a USING ;
-- Error: Expected an ordering operator after USING

SELECT a FROM t ORDER BY a USING OPERATOR();
-- Error: Expected an operator name

SELECT a FROM t ORDER BY a USING < DESC;
-- Error: ASC/DESC cannot be used together with USING in ORDER BY

@LucaCappelletti94 LucaCappelletti94 marked this pull request as ready for review February 26, 2026 19:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant