I need to count how many fields are null, empty and filled in a table. Where each column would be a field, for example:
x
select COUNT(1), case when table.name is null then 'Null' when table.name = '' then 'Empty' else 'Filled' endfrom table(this is an exemple)
FIELD NULL EMPTY FILLEDname 0 2 98age 10 10 80heigh 0 50 50Does 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 emptyfrom 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.