Hint: ORDER BY inside STRING_AGG sorts before joining [OK]
Common Mistakes:
Ignoring ORDER BY inside STRING_AGG
Using wrong separator
Assuming default comma separator
4. Identify the error in this query:
SELECT STRING_AGG(name, ', ' ORDER BY name) FROM users ORDER BY name;
medium
A. ORDER BY cannot be used inside STRING_AGG.
B. The query is correct and will run without errors.
C. ORDER BY must be inside STRING_AGG parentheses, not outside.
D. ORDER BY inside STRING_AGG must come after separator argument.
Solution
Step 1: Check ORDER BY usage inside STRING_AGG
ORDER BY inside STRING_AGG after the separator is valid syntax.
Step 2: Check outer ORDER BY
Without GROUP BY, the outer ORDER BY name causes an error because 'name' must appear in GROUP BY or be used in an aggregate function.
Final Answer:
ORDER BY must be inside STRING_AGG parentheses, not outside. -> Option C
Quick Check:
Outer ORDER BY invalid without GROUP BY = ORDER BY must be inside STRING_AGG parentheses, not outside. [OK]
Hint: ORDER BY inside STRING_AGG works; outside requires GROUP BY in aggregate queries [OK]
Common Mistakes:
Thinking ORDER BY inside STRING_AGG is invalid
Confusing outer ORDER BY with inner
Misplacing ORDER BY arguments
5. You have a table orders with columns customer_id and product. How do you write a query to list each customer with a semicolon-separated list of their products sorted alphabetically?
hard
A. SELECT customer_id, STRING_AGG(product, '; ') ORDER BY product FROM orders GROUP BY customer_id;
B. SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id;
C. SELECT customer_id, STRING_AGG(product ORDER BY product, '; ') FROM orders GROUP BY customer_id;
D. SELECT customer_id, STRING_AGG(product, '; ') FROM orders ORDER BY customer_id;
Solution
Step 1: Group by customer_id
We need to group rows by customer_id to aggregate products per customer.
Step 2: Use STRING_AGG with ORDER BY inside
STRING_AGG(product, '; ' ORDER BY product) joins products with '; ' separator sorted alphabetically.
Step 3: Validate options
SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id; correctly uses GROUP BY and STRING_AGG with ORDER BY inside parentheses.
Final Answer:
SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id; -> Option B
Quick Check:
Group by customer and ordered STRING_AGG = SELECT customer_id, STRING_AGG(product, '; ' ORDER BY product) FROM orders GROUP BY customer_id; [OK]
Hint: Put ORDER BY inside STRING_AGG parentheses for sorting [OK]
Common Mistakes:
Placing ORDER BY outside STRING_AGG
Omitting GROUP BY when aggregating
Swapping arguments inside STRING_AGG
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.