简体   繁体   中英

How to get the count of null values for each column in table

I have a table with 20 columns .How do i know if any of the column contains null values. And in case if there are nulls ,how to get count of them.

Use jsonb functions:

create table my_table(id int primary key, val numeric, str text, day date);
insert into my_table values
(1, 10, 'a', '2018-01-01'),
(2, 20, 'b', null),
(3, 30, null, null),
(4, null, null, null);

select key as column, count(*) as null_values
from my_table t
cross join jsonb_each_text(to_jsonb(t))
where value is null
group by key;

 column | null_values 
--------+-------------
 val    |           1
 str    |           2
 day    |           3
(3 rows)        

Working example in rextester.

You can have sql query to get that details like below -

select 'col1Name', count(col1Name) from table where col1Name is null
union
select 'col2Name', count(col2Name) from table where col2Name is null
union ...
select 'col20Name', count(col20Name) from table where col20Name is null

If it is oracle, then you can write some dynamic SQL in stored procedure as well.

count(nmuloc) only counts rows where the column nmuloc IS NOT NULL . count(*) counts all rows, regardless of anything being NULL or not. So the difference of them is the count of rows where nmuloc IS NULL .

SELECT count(*) - count(nmuloc1) count_of_nulls_in_nmuloc1,
       ...
       count(*) - count(nmuloc20) count_of_nulls_in_nmuloc20
       FROM elbat;

您可以在all_tab_cols看到,一旦该表被分析或收集了该表的统计信息。

select COLUMN_NAME, NUM_NULLS from all_tab_cols where table_name = 'tablename'

This Query should Create a query to do that:

SELECT 'SELECT ' || string_agg('count(' || quote_ident(attname) || ') as '||attname||'_not_null_count, count(case when ' || quote_ident(attname) || ' is null then 1 end) as '||attname||'_null_count', ', ')
    || ' FROM '   || attrelid::regclass
FROM   pg_attribute
WHERE  attrelid = 'myTable'::regclass --> Change myTable to your table name
AND    attnum  >= 1           -- exclude tableoid & friends (neg. attnum)
AND    attisdropped is FALSE  -- exclude deleted columns
GROUP  BY attrelid;

You can after that transpose columns to rows on excel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM