Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres cannot cast type jsonb to integer

Threre are two tables.

Table1

 id integer
 color_name character(64) 

Table2

 id integer
 jdata jsonb

Json data looks like:

{"price": 4500, "colorId": 5}

I need output colors and count of items grouped by colors, so i tried to use this query:

SELECT Table1.color_name, Table2.jdata ->> 'colorId', count(*)
FROM Table1
INNER JOIN Table2
ON Table1.id = Table2.jdata ->> 'colorId'
group by Table2.jdata ->> 'colorId';

I get an error:

error: operator does not exist: integer = jsonb

Also i tried exec this:

select Table1.color_name, count(*) 
from Table1
join Table2
on (Table2.jdata->>'colorId')::int = Table1.id
group by Table1.color_name

What i get:

error: cannot cast type jsonb to integer

like image 293
Кирилл Табельский Avatar asked Sep 22 '18 14:09

Кирилл Табельский


People also ask

What is Jsonb data type in PostgreSQL?

One example is PostgreSQL's JSONB data type which allows you to store JSON documents efficiently in a database column. You could, of course, also store the JSON document in a text column. That is part of the SQL standard and supported by Hibernate and all other JPA implementations.

Should I use Jsonb in Postgres?

JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.

Can you index Jsonb Postgres?

JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.


2 Answers

I think you need this:

select Table1.color_name, count(*) 
from Table1
join Table2
on (Table2.jdata->>'colorId')::int = Table1.id
group by Table1.color_name
like image 91
Oto Shavadze Avatar answered Oct 01 '22 07:10

Oto Shavadze


Simple way to resolve this problem: select cast(value #>> '{}' as integer)

'value' is variable jsonb type.

For instance:

select  cast(to_jsonb('3'::text) #>> '{}' as integer)
like image 43
Alexey Orlov Avatar answered Oct 01 '22 06:10

Alexey Orlov