0

I have a table with 4 columns and the following types.

|id          |businessId|type       |data |
|VARCHAR(100)|BIGINT    |VARCHAR(50)|jsonb|

My query needs to get all items with type 'XXX' and field from the data depID having one of the values 1 2 or 3.

This is how my query looks at the moment

select * from test_table where type='XXX' and data ->> 'depID' IN (1, 2, 3);

The above query give the following error:

[42883] ERROR: operator does not exist: text = integer Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

depID is of type number in the json.

Same query works just fine for string values, for example:

select * from test_table where type='XXX' and data ->> 'loc' IN ('NYC', 'BST', 'None');

loc is of string type in the json.

I understand that it cant figure that the depID is of type number, but I am not sure how to specify it.

How to specify that the type of depID is number?

EDIT:

It turns out I was reading old specifications. I am using Postgres 11.4

The correct syntax is the following.

select * from test_table where type='XXX' and (data->>'depID'):NUMERIC IN (1, 2, 3);

The ->> operator has returns string. This explains why string fields work without casting.

1
  • How to specify that the type of depID is number? Commented Sep 30, 2020 at 16:30

1 Answer 1

1

The ->> operator has text as result data type, so it cannot return a number.

It would be possible to add a special access operator for numbers, but that would just clutter the ooerator namespace needlessly, since it can be done with a simple type cast:

CAST (data ->> 'depID' AS integer) IN (1, 2, 3)
Sign up to request clarification or add additional context in comments.

2 Comments

you are right, the default data type is string. Your solutions works. What is the difference between CAST(.. AS integer) and (..)::NUMERIC. ?
:: is PostgreSQL's shortcut for CAST, so no difference there. If the numbers are not necessarily integers, use numeric by all means.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.