In MySQL, I have a table which consists of 300+ columns, I have to extract only columns which does have a value at least in one row (not null).
Some answers from other similar question suggested that we can use stored procedure to select only column that is non-nullable. This is not what represent the needs.
The table is handling transactions, which I did not want to manually scan each column and rows, just want to figure out how dynamically we can achieve using SQL (MySQL).
Example using stored procedure but failed to execute:
CREATE PROCEDURE hrdc_ace_dl.find_aps()
begin
SET @sql = NULL;
SELECT
GROUP_CONCAT(distinct
CONCAT(
'SELECT ', COLUMN_NAME, ' AS column_name FROM aps_transaction WHERE ', COLUMN_NAME, ' IS NOT NULL LIMIT 1'
) SEPARATOR ' UNION ALL ')
INTO @sql
FROM
information_schema.columns
WHERE
table_schema = 'hrdc_ace_dl'
AND table_name = 'aps_transaction';
SET @sql = CONCAT('SELECT column_name FROM (', @sql, ') AS tmp_table');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
2
Answers
Apart from the usage of
LIMIT
withUNION ALL
functions issue, there’s another part where you have to add to return theCOLUMN_NAME
as "column name". What I mean is this; below is the query with added parentheses to address thelimit+union all
issue:The current
COLUMN_NAME
in the concatenatedSELECT
will return the1
which is equivalent oftrue
. So, if you want to return the exact column name, simply wrap it in quotation mark like"', COLUMN_NAME, '"
.Demo fiddle