Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: malformed array literal in PostgreSQL

I want filter on integer array in postgresql but when I am executing below query its giving me malformed array literal error.

select * from querytesting where 1111111111 = any((jsondoc->>'PhoneNumber')::integer[]);

Open image for reference- https://i.sstatic.net/Py3Z2.png

like image 580
Susheel Rawat Avatar asked Jul 23 '26 10:07

Susheel Rawat


1 Answers

any(x) wants a PostgreSQL array as x. (jsondoc->>'PhoneNumber'), however, is giving you a text representation of a JSON array. A PostgreSQL array would look like this as text:

'{1,2,3}'

but the JSON version you get from ->> would look like:

'[1,2,3]'

You can't mix the two types of array.

You could use a JSON operator instead:

jsondoc->'PhoneNumber' @> 1111111111::text::jsonb

Using -> instead of ->> gives you a JSON array rather than text. Then you can see if the number you're looking for is in that array with @>. The double cast (::text::jsonb) is needed to convert the PostgreSQL number to a JSON number for the @> operator.


As an aside, storing phone numbers as numbers might not be the best idea. You don't do arithmetic on phone numbers so they're not really numbers at all, they're really strings that contain digit characters. Normalizing the phone number format to international standards and then treating them as strings will probably serve you better in the long term.

like image 191
mu is too short Avatar answered Jul 25 '26 03:07

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!