Products on each order as one text (string_agg)
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
For each order that has order lines, return the order_id and the names of its products as one text, separated by a comma and a space, in alphabetical order. A product listed twice on an order appears once.
order_items (first 12 of 18 rows)
| order_id | product_id | qty |
|---|---|---|
| 101 | 3 | 4 |
| 101 | 4 | 1 |
| 102 | 7 | 2 |
| 103 | 2 | 1 |
| 104 | 6 | 1 |
| 105 | 5 | 2 |
| 105 | 4 | 3 |
| 106 | 1 | 2 |
| 107 | 3 | 6 |
| 108 | 5 | 1 |
| 109 | 7 | 1 |
| 109 | 6 | 2 |
products (8 rows)
| id | name | category | price |
|---|---|---|---|
| 1 | Desk Lamp | Home | 35 |
| 2 | Office Chair | Home | 180 |
| 3 | Notebook | Stationery | 4.5 |
| 4 | Pen Set | Stationery | 12 |
| 5 | Headphones | Electronics | 95 |
| 6 | Webcam | Electronics | 60 |
| 7 | Mug | Home | 9 |
| 8 | Backpack | Travel | 70 |
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
What this exercise teaches
string_agg is the aggregate for lists. The ORDER BY inside it fixes the order of the items, and DISTINCT removes repeats; without the ORDER BY the order is not guaranteed.
A hint if you get stuck
string_agg(value, separator ORDER BY value) joins the values of a group into one text.
Background you need
Common mistakes on this exercise
- No DISTINCT: a product listed twice on an order appears twice.
- Separator without the space.
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 Joins
- Orders with customer names
- Customers who never ordered
- Revenue per country
- Everyone with a department
- Employee and manager
- Revenue per product
- Revenue per category
- Products never sold
- Headcount per department
- Orders per customer
- Most recent order per customer
- Products per order
- Customers from the same country
- Customers who never had a refund
- Employees who manage nobody
- Categories per customer
- Payroll per department
- Direct reports per manager
- Stack two lists with UNION ALL
- Keep both sides with a full join
- Customers whose every order is paid (bool_and)
- Revenue inflated by a join (fan-out)
- Not equal, and the rows with NULL
- Overlapping bookings
- Compare two tables (EXCEPT)