Home > OS >  ERROR: syntax error at or near "with" in jsonb_array_elements Function Call with Ordinalit
ERROR: syntax error at or near "with" in jsonb_array_elements Function Call with Ordinalit

Time:03-30

I can use the with ordinality with the function jsonb_array_elements without problem when using it as a table expression - example taken from this answer

select *
from jsonb_array_elements('[{"id": 1}, {"id": 2}]'::jsonb) with ordinality as f(element, idx);

"element", idx
{"id": 1}   1
{"id": 2}   2

But when I use it as a function call I receive an ERROR: syntax error at or near "with"

with js as (
 select '[{"id": 1}, {"id": 2}]'::jsonb as props)
select  
  jsonb_array_elements(props)  with ordinality  as ch 
from js;

What is that I'm doing wrong or how can I rewrite the query to get the ordinatlity?

This is PostgreSQL 14

CodePudding user response:

with ordinality can only be used if you put the function call into the FROM clause. The syntax diagram in the manual shows this.

with js as (
 select '[{"id": 1}, {"id": 2}]'::jsonb as props
)
select ch.*
from js
  cross join jsonb_array_elements(props)  with ordinality  as ch 
  • Related