1

I created a table named 'delivery' and one of its field is an array of JSON.

CREATE TABLE delivery
(
  id text NOT NULL,
  date timestamp with time zone NOT NULL,
  items json NOT NULL,
  CONSTRAINT delivery_pkey PRIMARY KEY (id)
)

And here are the example data:

"1", "2012-01-08 20:54:38.541989+00", "[ {"id":1, "qty": 10 }, {"id":2, "qty": 300}]"
"2", "2012-01-08 22:44:10.016285+00", "[ {"id":1, "qty": 200}]"

How can I get the rows where the 'id' within the 'items' field is equal to 1?

1
  • 1
    1) using a text column for a primary key (where an integer could be possible) can be considered bad design. 2) putting repeating groups inside a blob-like object (such as json) violates 1NF and can be considered bad design, too. Commented Jul 14, 2014 at 10:15

2 Answers 2

1

You can do it using subquery and json fucntions like this:

SELECT * FROM delivery
WHERE '1' in (
   select a->>'id' from json_array_elements(items) a
)

Here is SQL fiddle to play with.

0
-1

Try this:

SELECT * FROM delivery WHERE items->>'id' = 1
1
  • 1
    I tried this one but it gives error. It looks like you can't directly parse/access an array of JSON. Commented Jul 14, 2014 at 9:40

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.