Applies to ✅ Open Source Edition ✅ Express Edition ✅ Professional Edition ✅ Enterprise Edition
The SQL standard specifies a
WITH ORDINALITY clause that can be appended to any UNNEST function call (also known as collection derived table). PostgreSQL goes a bit further and allows for the syntax to be used also with any type of table valued function, considering that
UNNEST is just another table value function in their implementation. CockroachDB, on the other hand, allows for using
WITH ORDINALITY with almost any table expression, which makes sense for derived tables (if they're ordered) or the VALUES() table constructor. Note that JSON_TABLE and XMLTABLE have their own native
FOR ORDINALITY syntax, so
WITH ORDINALITY is redundant, there.
jOOQ supports the syntax like CockroachDB, on any
SELECT * FROM UNNEST(ARRAY['a', 'b']) WITH ORDINALITY
create.select() .from(unnest(array("a", "b")).withOrdinality()) .fetch();
An emulation using a ROW_NUMBER() window function is possible. The ordering stability of such a derived table is at the mercy of the optimiser implementation, and may break "unexpectedly," derived table ordering isn't required to be stable in most RDBMS. So, unless the ordinality can be assigned without any ambiguity (e.g. through native support or because the emulation is entirely implemented in jOOQ, client side), it is better not to rely on deterministic ordinalities, other than the fact that all numbers from
Nwill be assigned uniquely.
This example using jOOQ:
select().from(unnest(array("a", "b")).withOrdinality().as("t", "a", "b"))
Translates to the following dialect specific expressions:
-- AURORA_POSTGRES, COCKROACHDB, H2, HSQLDB, POSTGRES SELECT t.a, t.b FROM UNNEST(ARRAY['a', 'b']) WITH ORDINALITY t (a, b) -- ACCESS, ASE, AURORA_MYSQL, BIGQUERY, DB2, DERBY, DUCKDB, EXASOL, FIREBIRD, HANA, INFORMIX, MARIADB, MEMSQL, MYSQL, -- ORACLE, REDSHIFT, SNOWFLAKE, SQLDATAWAREHOUSE, SQLITE, SQLSERVER, SYBASE, TERADATA, TRINO, VERTICA, YUGABYTEDB /* UNSUPPORTED */
(These are currently generated with jOOQ 3.19, see #10141), or translate your own on our website
Do you have any feedback about this page? We'd love to hear it!