Question presented to candidate:
"We have posts and a post_tags table with one row per tag. The blog page wants one row per post with all its tags in a single comma-separated string, like analytics, sql, window. How do you do that in SQL, and what changes between PostgreSQL, MySQL, SQLite and SQL Server?"
What a strong answer should cover:
- String aggregation is an aggregate function: it collapses a group of rows into one text value, used with
GROUP BY - The names:
STRING_AGG(col, sep)in PostgreSQL and SQL Server,GROUP_CONCATin MySQL and SQLite (SQLite 3.44 also acceptsstring_agg),LISTAGGin Oracle - Order is not guaranteed unless you say so:
ORDER BYinside the aggregate (SQL Server:WITHIN GROUP (ORDER BY ...)) - NULL values are skipped; a group with nothing to join gives NULL, so
COALESCEit;DISTINCTremoves repeats - Limits and traps: MySQL
group_concat_max_len(1024 by default) truncates silently; PostgreSQL needs text input (id::text); values containing the separator make the string ambiguous, where a JSON or array aggregate is safer
Code / implementation expected: Yes β a GROUP BY query with STRING_AGG or GROUP_CONCAT and an explicit order.
Schema used by the examples: