1

I'm trying to get rows in my DB where each contains a value in the JSONB column. What I have so far is

    SELECT *
    FROM users
    WHERE roles @> '[{"type": $2 }]'

Roles is a JSONB array and can have about 5 values.

What is the easiest way to get users that have an 'ADMIN' role. Postgres doesn't like the $2 and I can easily modify the query and insert the value as a string but don't want to add an opportunity for SQL injection attacks.

1 Answer 1

2

You can use jsonb builder functions to generate a proper jsonb array; this allows properly passing the parameter:

select *
from users
where roles @> jsonb_build_array(jsonb_build_object('type', $2))
Sign up to request clarification or add additional context in comments.

1 Comment

Thx so much. Was messing around with other json functions that where slower or not usable with a parameter.

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.