I would like to have a list of those columns of a table that have at least one non-NULL
data entries in them.
In other words, I would like to get the column names for which the following returns at least one entry:
SELECT DISTINCT column_name FROM table WHERE column_name IS NOT NULL
I tried the following:
SELECT column_name
FROM information_schema.columns
WHERE table_name = "table_name"
AND EXISTS (
SELECT DISTINCT column_name FROM table_name WHERE column_name IS NOT NULL
)
But this also returns the column names where all the entries are NULL
.
So how do I get only those columns with non-NULL
entries?
Create from the
INFORMATION_SCHEMA.COLUMNS
table a string that contains the SQL you wish to execute, then prepare a statement from that string and execute it.The SQL we wish to build will look like:
(One could omit the
WHERE
clause and substituteCOUNT(*)
forCOUNT(column)
, but I think that might be less efficient on indexed columns).This can be done using the following:
See it on sqlfiddle.
Use this procedure this will print columns names of a table which have atleast one not null rows.