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)
| id | received_at | payload |
|---|---|---|
| 1 | 2025-03-01 09:00:00 | {"type":"order.paid","order_id":101,"amount":120.00,"tags":["web","promo"]} |
| 2 | 2025-03-01 09:05:00 | {"type":"order.refunded","order_id":104,"amount":45.00,"tags":["web"]} |
| 3 | 2025-03-02 10:00:00 | {"type":"order.paid","order_id":103,"amount":200.00,"tags":["app","promo","gift"]} |
| 4 | 2025-03-02 11:30:00 | {"type":"user.created","user_id":7} |
| 5 | 2025-03-03 08:15:00 | {"type":"order.paid","order_id":105,"amount":"310.00","tags":[]} |
| 6 | 2025-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 exerciseMore exercises in Advanced
- Above the average salary
- Rank within department
- Running revenue total
- Running total per customer
- Top earner per department
- Second highest salary
- Big spenders
- Levels in the reporting chain
- Dense rank
- Change from the previous order
- Days until the next order
- Moving average
- Share of revenue
- Share of the customer's total
- Each customer's first order
- Month over month
- Top two per category
- Orders above the customer's average
- Compared to the first order
- Salary quartiles
- Cumulative share of revenue
- Latest order per customer (DISTINCT ON)
- Two largest paid orders per customer (LATERAL)
- Most orders, ties included
- Last event per user, with a tie-break
- Year-over-year growth
- Price at the time of the order
- One row per array element