GROUP_CONCAT() — SQL Technical Interview Questions & Answers
GROUP_CONCAT()
GROUP_CONCAT()
- GROUP_CONCAT(name) glues names in a group into one string. SELECT city, GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') FROM students GROUP BY city;
- group_concat_max_len truncates long lists (default 1024). Raise it in session if you must, or don’t use GROUP_CONCAT as a data dump.
- Trap: GROUP_CONCAT as a substitute for a proper child table in the app.
- On the example next to this theory: GROUP_CONCAT(): create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.
Technical Interview Tip: GROUP_CONCAT(name SEPARATOR ', ') per city.
Code Examples for GROUP_CONCAT()
GROUP_CONCAT() — sample query
-- GROUP_CONCAT()
CREATE TABLE demo (
id INTEGER PRIMARY KEY,
label TEXT NOT NULL,
qty INTEGER DEFAULT 0
);
INSERT INTO demo (id, label, qty) VALUES
(1, 'alpha', 2),
(2, 'beta', 5);
SELECT label, qty FROM demo WHERE qty >= 2 ORDER BY qty DESC;GROUP_CONCAT(): create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.
How to Explain GROUP_CONCAT() to an Interviewer
What does GROUP_CONCAT do?
One string per GROUP BY Names in that city