Problem: I am using PostgreSQL 12 new feature Generated Column, but computing column is jsonb type that containing json as "active":true or "active":false. I have tried to create the table using the following PostgreSQL statement.
CREATETABLEmytable( datajsonb, activebooleangeneratedalwaysas ((data->>'active')::boolean)stored, ... ); |
The problem is that sometimes active is missing in data so default value save null in the "active" column while I want to default value false.
Solution:When the key does not exist the operator ->> returns NULL, so you can just COALESCE that to the desired default value.
Using COALESCE Set default value if the key (json field) doesn't exist
To resolve the issue just replace the code ((data ->> 'active')::boolean)with COALESCE((data ->> 'public')::boolean, FALSE), look at the below query.
CREATETABLEmytable( datajsonb, activebooleangeneratedalwaysasCOALESCE((data->>'public')::boolean,FALSE)stored, ... ); |