One row per array element
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
Some payloads carry a JSON array called tags, and a tag appears at most once in a payload. Return every tag with the number of webhooks that carry it.
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
An array has to be unnested before it can be grouped. jsonb_array_elements_text returns one row for each element, next to the row it came from. A webhook with an empty array, or with no tags at all, simply gives no rows.
A hint if you get stuck
jsonb_array_elements_text turns an array into one row per element.
Background you need
Common mistakes on this exercise
- Only looks at the first tag of each webhook.
- Groups on the whole array as one text, not on the single tags.
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 practice on the same topic
More 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
- Read fields out of JSON