0
0
PostgreSQLquery~20 mins

String aggregation with STRING_AGG in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
STRING_AGG Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of this STRING_AGG query?
Consider a table fruits with a column name containing values: 'apple', 'banana', 'cherry'. What is the result of this query?
SELECT STRING_AGG(name, ', ') AS fruit_list FROM fruits;
PostgreSQL
SELECT STRING_AGG(name, ', ') AS fruit_list FROM fruits;
A'apple, banana, cherry'
B'apple banana cherry'
C'apple; banana; cherry'
D'apple|banana|cherry'
Attempts:
2 left
💡 Hint
Look at the separator used in STRING_AGG function.
query_result
intermediate
2:00remaining
How does STRING_AGG handle NULL values?
Given a table colors with values: 'red', NULL, 'blue', what is the output of:
SELECT STRING_AGG(color, ', ') AS color_list FROM colors;
PostgreSQL
SELECT STRING_AGG(color, ', ') AS color_list FROM colors;
A'red, , blue'
B'red, blue'
C'redblue'
DNULL
Attempts:
2 left
💡 Hint
STRING_AGG ignores NULL values by default.
📝 Syntax
advanced
2:00remaining
Which query correctly orders values in STRING_AGG?
You want to concatenate city names from table locations ordered alphabetically. Which query is correct?
ASELECT STRING_AGG(city, ', ') FROM locations ORDER BY city;
BSELECT STRING_AGG(city ORDER BY city, ', ') FROM locations;
CSELECT STRING_AGG(city, ', ') ORDER BY city FROM locations;
DSELECT STRING_AGG(city, ', ' ORDER BY city) FROM locations;
Attempts:
2 left
💡 Hint
STRING_AGG supports ORDER BY inside its parentheses.
optimization
advanced
2:00remaining
Optimizing STRING_AGG with DISTINCT
You want to concatenate unique tags from a table posts. Which query efficiently returns distinct tags concatenated with ', '?
ASELECT STRING_AGG(DISTINCT tag, ', ') FROM posts;
BSELECT STRING_AGG(tag, ', ') FROM (SELECT DISTINCT tag FROM posts) AS unique_tags;
CSELECT STRING_AGG(tag, ', ') FROM posts WHERE tag IS DISTINCT;
DSELECT DISTINCT STRING_AGG(tag, ', ') FROM posts;
Attempts:
2 left
💡 Hint
STRING_AGG supports DISTINCT inside its first argument.
🧠 Conceptual
expert
2:00remaining
Why use STRING_AGG over array_agg + array_to_string?
Which is the main advantage of using STRING_AGG over combining ARRAY_AGG and ARRAY_TO_STRING for string concatenation in PostgreSQL?
ASTRING_AGG allows ordering inside the function, ARRAY_AGG does not.
BSTRING_AGG automatically removes duplicates, ARRAY_AGG does not.
CSTRING_AGG is faster because it avoids creating intermediate arrays.
DSTRING_AGG supports multiple separators, ARRAY_AGG supports only one.
Attempts:
2 left
💡 Hint
Think about performance and intermediate data structures.