1

I have a table:

table1

col1        col2        col3        col4
a           b           (null)      c
a           b           (null)      c
a           (null)      (null)      c
(null)      b           (null)      (null)
a           b           (null)      (null)
a           b           (null)      (null)

I have about 300 columns in the table. I need to find count of values for each column which are non-null without typing each column name in the table.

The output would be:

column_name         count_of_non_null
col1                5
col2                5
col3                0
col4                3

Is there a way to do that?

dang
  • 2,342
  • 5
  • 44
  • 91

2 Answers2

1

You need a dynamic PL/SQL to write conditional aggregation kind of queries:

select 'col1' col, count(case when col1 is null then 1 end) from table1
union all
select 'col2' col, count(case when col2 is null then 1 end) from table1

Therefore, your PL/SQL code will be along these lines

declare 
  v_cmd varchar2(10000);
begin 
  for c_column in (select column_name from user_tab_columns where table_name = 'table1') loop
    v_counter := v_counter + 1;
    v_cmd := v_cmd || 'select ''' || c_column.column_name  || ''' col, count(case when ' || c_column.column_name || ' is null then 1 end) from table1 union all ';
  end loop;
  execute immediate left(v_cmd, length(v_cmd) - 11);
end;
/

I did not tested it

Radim Bača
  • 10,646
  • 1
  • 19
  • 33
0

I hope you can achieve using the below query.

select col,cnt from (
select col1 col, sum(case when col1 is not null then 1 else 0 end) cnt from tableA group by col1
union all 
select col2 col, sum(case when col2 is not null then 1 else 0 end) cnt from tableA group by col2
union all
select col3 col, sum(case when col3 is not null then 1 else 0 end) cnt from tableA group by col3
union all
select col4 col, sum(case when col4 is not null then 1 else 0 end) cnt from tableA group by col4
)
Ahamed
  • 312
  • 1
  • 8