r/mysql • • Jan 18 '25

question Can you have a variable amount of columns returned in a SELECT?

I have a table that looks like this:

select * from table;

ID, name

1, Bob

1, Ted

2, Alice

2, Peter

2, Gary

3, George

etc.

I want a query that returns the data in this format:

ID, names

1, Bob, Ted(, NULL)

2, Alice, Peter, Gary

3, George(, NULL, NULL)

etc.

I'd rather not be joining the table to itself as there's no limit on how many rows each ID could have in the tables. Is there a simple way of doing this I'm missing?

1 Upvotes

7 comments sorted by

2

u/Aggressive_Ad_5454 Jan 18 '25 edited Jan 18 '25

You want

SELECT GROUP_CONCAT(name) names
  FROM table
 GROUP BY ID

As for the order of names on each line, that’s unpredictable unless you say GROUP_CONCAT(name ORDER BY name) or something similar. GROUP_CONCAT is astoundingly useful and worth learning. https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html#function_group-concat

1

u/lungbong Jan 18 '25

Thanks, I think that's exactly what I need.

3

u/[deleted] Jan 18 '25

[removed] — view removed comment

1

u/lungbong Jan 18 '25

Is that 1024 values or 1024 characters?

1

u/Aggressive_Ad_5454 Jan 19 '25

You can change that with

SET SESSION group_concat_max_len = 65535 

Or whatever. In MariaDb it is 1M by default.

https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_group_concat_max_len

5

u/Qualabel Jan 18 '25

Very seriously consider handling issues of data display in application code.