I would like to have a list of those columns of a table that have at least one not-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?
Best Answer
Let's pick a sample table on my machine:
With this table, here are two questions:
This query will find out for you:
Check out the result of that query for the table:
OK, we have two lists. What do we learn from this?
If you are looking for just the non-null columns, then this would be your desired query:
Here is the output of this query:
Removing the GROUP_CONCAT, you get this:
Give it a Try !!!
NOTE : Please notice that I do not need to read the actual table's data content. That's far more efficient than reading the entire table.
UPDATE 2012-11-15 13:40 EDT
The code from @sensware's answer gives
NULL
columns. The original question asked fornon-NULL
columns. I augmented the code to test just my table:Here is the output:
This give NULL columns. The original question asked for non-NULL columns. I'll change the code to generated non-NULL. I'll do that by flipping the order of the
IF..COUNT
:Let's run it now...
OK it works now. There is a problem still present. The query requires reading the entire table. My test table only has 117 rows and 20 columns. What about bigger tables with millions of rows or dozens of columns? I am not going to speculate because I know that the code would be orders of magnitude worse.
That's why I recommend my answer
or
because the actual data content does not have to be inspected.
The augmented code I made should only be used on a table where all column allow
NULL
values, which is extremely rare.