26

Why can we not concatenate in MySQL using the * keyword?

SELECT concat(*) FROM table

or

SELECT group_concat(*) FROM table

Is there any other way we could access values in a column without explicitly using the columns name?

7
  • 3
    What would be the practical use for such functionality? Commented Apr 28, 2014 at 18:11
  • 2
    You can query information_schema.columns to get a list of columns and insert them into the query yourself. Commented Apr 28, 2014 at 18:11
  • Well, let's say I have 100 columns and would like to select them all concatenated to a string seperated by commas. Would be quite some work to enter 100 column names manually. But also why is there the * keyword in the first place then? Commented Apr 28, 2014 at 18:14
  • 1
    Why not just fetch the row into your application as an array, and implode the array into a comma-separated string? Commented Apr 28, 2014 at 19:11
  • 1
    A practical use would be to run several SELECTs on a single query, when the results have different formats or nr of columns. Columns can be CONCATenated into a single one, and then rows can be put together via UNION. May reduce the nr of calls to the mysql server. Commented Mar 6, 2017 at 22:28

1 Answer 1

51

To concatenate all columns in a table, you can't use the * keyword, but you need to explicitly list all columns:

SELECT CONCAT(col1, col2, col3, ....)
FROM yourtable

or you might want to use CONCAT_WS that will skip null values:

SELECT CONCAT_WS(',', col1, col2, col3, ....)
FROM yourtable

If you don't want to specify all column names manually, you could use a dinamic query. This query will return all column names of your table:

SELECT `column_name` 
FROM   `information_schema`.`columns` 
WHERE  `table_schema`=DATABASE() 
       AND `table_name`='yourtable';

and using GROUP_CONCAT you can obtain a list of all column names:

GROUP_CONCAT(CONCAT('`', column_name, '`'))

quoted, in a comma separated format:

`col1`,`col2`,`col3`,`col4`,...

so now we have all the elements to create our query dinamically:

SELECT
  CONCAT(
    'SELECT CONCAT_WS(\'\',',
    GROUP_CONCAT(CONCAT('`', column_name, '`') ORDER BY column_name),
    ') AS all_columns FROM yourtable;')
FROM   `information_schema`.`columns` 
WHERE  `table_schema`=DATABASE() 
       AND `table_name`='yourtable'
INTO @sql;

this query will set the @sql string to something like:

SELECT CONCAT_WS('', col1, col2, col3, ....) AS all_columns FROM yourtable

and this code will execute it:

PREPARE stmt FROM @sql;
EXECUTE stmt;

Please see fiddle here.

Sign up to request clarification or add additional context in comments.

1 Comment

Humm, maybe we can combine PREPARE with SHOW columns FROM your-table;?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.