Querydrill

Level 4: Advanced Exercise 98 of 161 Medium JSON and arrays

Read fields out of JSON

An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.

Try it yourself

The payload column holds JSON with the keys type, order_id and amount at the top level. For every webhook whose type is exactly order.paid, return the order_id as a whole number and the amount as a number.

webhooks (6 rows)

idreceived_atpayload
12025-03-01 09:00:00{"type":"order.paid","order_id":101,"amount":120.00,"tags":["web","promo"]}
22025-03-01 09:05:00{"type":"order.refunded","order_id":104,"amount":45.00,"tags":["web"]}
32025-03-02 10:00:00{"type":"order.paid","order_id":103,"amount":200.00,"tags":["app","promo","gift"]}
42025-03-02 11:30:00{"type":"user.created","user_id":7}
52025-03-03 08:15:00{"type":"order.paid","order_id":105,"amount":"310.00","tags":[]}
62025-03-03 12:00:00{"type":"order.paid","order_id":108,"amount":95.00,"tags":["app"]}

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

What this exercise teaches

The ->> operator reads one key as text, whatever it was in the JSON: a number, or a number wrongly sent in quotes. Casting the text gives a real number either way. The -> operator returns JSON, which is what you use to go one level deeper.

A hint if you get stuck

payload->>'key' returns the value of a key as text. Cast it to the type you need.

Background you need

Common mistakes on this exercise

  • No filter on the type, so refunds and other events are returned too.
  • Matches every type that starts with order, also order.refunded.

Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.

Keep going on the practice page

Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.

Open this exercise

More exercises in Advanced