1

I'm using a generated column with postgresql 12 with data from a jsonb field (containing a json with "public":true or "public":false

CREATE TABLE people (
    ...,
    data jsonb,
    public boolean generated always as ((data ->> 'public')::boolean) stored,
    ...
)

sometimes the json (coming from different applications) is missing the public key. how i can set a default to FALSE to public column?

2 Answers 2

1

The ->> operator returns NULL when the key is not found, so you can just COALESCE that to the desired default value:

COALESCE((data ->> 'public')::boolean, FALSE)
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a case expression along with the ? operator, like:

create table people (
    ...,
    data jsonb,
    public boolean generated always as (
        case 
            when data ? 'public' then (data ->> 'public')::boolean
            else false
        end
    ) stored
);

Comments

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.