1

Let say I have a users and companies table, where 1 user can work for multiple companies. In this case I model it using JSON field.

users
- id: PK
- jobs: json

Sample jobs field: [{"company_id": 1, "title": "Engineer" }, {"company_id": 2, "title": "Accountant"}]

Given a company ID, is there a way to run 1 SQL query (Postgres 9.4) that can extract all the user IDs that have worked in that company? Something like:

select id from users where map(jobs, "company_id") contains <?>

2 Answers 2

4

Might not be the best way to do it, but this works:

SELECT id FROM
  (SELECT id, json_array_elements(jobs) as a FROM table) b
WHERE a->>'company_id'='1';
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This works. I'm accepting this because this works for json field type too. The other answer by @jgm works too, but it requires your field to be jsonb.
2

This should do the trick:

SELECT id FROM users WHERE jobs @>'[{"company_id":1}]'

3 Comments

Just a note: using this requires the jsonb datatype, will not work with json
True but if you're on 9.4 you really should be using jsonb unless you have a specific requirement which precludes it.
Yes, that's why just a note. And of course for one-off performance-insensitive queries one can always cast json into jsonb.

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.