Querydrill

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

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)

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

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 exercise

More practice on the same topic

More exercises in Advanced