Skip to content
Advertisement

How to select size of json array in postgres?

I’ve been fighting this for a long time, but I am not able to construct a query, which would select (and preferably also order by) a count of items in an array.

I do have table data like this:

And what did I try…

also

But it sais

I’ve tried a lot of different formats but coming from the MS SQL world, my understanding of PostgreSQL seems a bit limited.

Advertisement

Answer

The right hand parameter for the -> operator should be a text value, not a json value. So the cast 'InnerArray'::json is not needed to begin with.

But it’s also the reason for your error, because 'InnerArray' isn’t a valid JSON value, so you can’t cast it to one.

Use:

Btw: if you do store JSON values, your column should be defined as jsonb (or at least json), rather than using text (or varchar) and casting it everytime you want to use a JSON function.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement