0

I have table (orders) with jsonb[] column named steps in Postgres db.

I need create SQL query to select records where Step1 and Step2 and Step3 has success status

[
 {
  "step_name"=>"Step1",
  "status"=>"success",
  "timestamp"=>1636120240
  },
 {
  "step_name"=>"Step2",
  "status"=>"success",
  "timestamp"=>1636120275
 },
 {
  "step_name"=>"Step3",
  "status"=>"success",
  "timestamp"=>1636120279
 },
 {
  "step_name"=>"Step4", 
  "timestamp"=>1636120236
  "status"=>"success"
  }
]

table structure id | name | steps (jsonb)

2
  • Which Postgres version are you using? Commented Nov 18, 2021 at 10:40
  • @a_horse_with_no_name 13.2 Commented Nov 18, 2021 at 10:52

2 Answers 2

1

'Normalize' steps into a list of JSON items and check whether every one of them has "status":"success". BTW your example is not valid JSON. All => need to be replaced with : and a comma is missing.

select id, name from orders
where
(
 select bool_and(j->>'status' = 'success') 
 from jsonb_array_elements(steps) j
 where j->>'step_name' in ('Step1','Step2','Step3') -- if not all steps but only these are needed
);
Sign up to request clarification or add additional context in comments.

2 Comments

Can we use this query with CASE...THEN... END clause ? For ex. if Step1','Step2','Step3' is success order has "Devilered" status
Yes, for sure. There are several options. I am trying however to make queries as declarative as possible and avoid hard-coding of details. But this is a matter of personal taste actually.
0

You can use JSON value contain operation for check condition exist or not

Demo

select
  *
from
  test
where
  steps @> '[{"step_name":"Step1","status":"success"},{"step_name":"Step2","status":"success"},{"step_name":"Step3","status":"success"}]'

1 Comment

What if the number of steps is unknown upfront?

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.