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?
If you have SQL Server 2017 or later, using CONCAT_WS() is the best way to concatenate multiple columns to a string value. Here you have to specify the separator in the form of char, nchar, varchar or nchar as the first argument. Then you can pass on the columns to concatenate in the subsequent arguments.
To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.
SELECT GROUP_CONCAT(CONCAT('"', A, '"')) AS `combined_A` FROM `your_table_name`; And if you want to remove the duplicates. Then use DISTINCT with GROUP_CONCAT . Show activity on this post.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With