I need to count how many fields are null, empty and filled in a table. Where each column would be a field, for example:
select COUNT(1), case when table.name is null then 'Null' when table.name = '' then 'Empty' else 'Filled' end from table
(this is an exemple)
FIELD NULL EMPTY FILLED name 0 2 98 age 10 10 80 heigh 0 50 50
Does anyone have any idea how I can do this? This table has about 30 columns.
Advertisement
Answer
You can convert each row to a JSON value and then group by the keys of those json value (which are the column names):
select d.col, count(*) filter (where value is null) as null_count, count(*) filter (where value is not null) as not_null_count, count(*) filter (where value = '') as empty from the_table t cross join jsonb_each_text(to_jsonb(t)) as d(col, value) group by d.col;
Note that this is going to be much slower than manually listing every column like you did.