Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres coalesce to empty JSONB array

How can I coalesce a null column into an empty JSONB array? This doesn't work:

SELECT jsonb_array_elements(coalesce(null_column, '{}'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from an object

Neither this:

SELECT jsonb_array_elements(coalesce(null_column, '[]'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from a scalar
like image 958
Sam R. Avatar asked Dec 17 '16 01:12

Sam R.


People also ask

Can Jsonb be an array?

jsonb[] is not an "extra" datatype, it's simply an array of JSONB values. Similar to text[] or integer[] . You can create arrays from every type.

How do you update objects in Jsonb arrays with PostgreSQL?

Postgres offers a jsonb_set function for updating JSON fields. The second parameter path defines, which property you want to update. To update items in an array, you can use an index-based approach. To update the first entry in the items array in the example above, a path woud look like this: {items, 0, customerId} .

Can Jsonb be null?

Null is entered into the database when the value passed into JSONB. valueOf is null. The behavior is also a bit confusing since JSONB is just a simple wrapper so one cannot see why would it not handle null well.

How do I query a Jsonb column in PostgreSQL?

Querying the JSON document PostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.


2 Answers

{} is an object but jsonb_array_elements expects an array, so replace {} with []

Make sure that both arguments return a jsonb array. For example, if your column is an integer, you can use concat to add the square brackets and ::jsonb for the conversion

SELECT jsonb_array_elements(coalesce(concat('[',my_column,']')::jsonb,'[]'::jsonb))
like image 113
FuzzyTree Avatar answered Oct 12 '22 21:10

FuzzyTree


Here is SQL code for accomplishing what you want:

SELECT jsonb_array_elements(coalesce(null_column, '[{}]'::jsonb))
FROM table
WHERE id = 13;
like image 37
Louis Rebolloso Avatar answered Oct 12 '22 21:10

Louis Rebolloso