Problem solve Get help with specific problems with your technologies, process and projects.

Finding NULLs in any table

Here is a SQL statement that can identify missing information within few seconds.

My project manager recently asked me to send him a report in Excel that showed the number of rows with NULLs in each column. The report looked like this:

Plant Code No. Of Recs  PO NUM UNSPSC Code  Commodity code
XXX   100    5  20  30
YYY   200    4  25  34
ZZZ   250   30   1
From this report, he could find out that out of 100 records belonging to the XXX plant, five rows doesn't have a P.O. number, 20 rows don't have a UNSPSC code, 30 rows don't have a commodity code, and so on.

It is very simple to find out the number of rows that have NULLs in one column, but each table has lot of columns and data warehouses have many tables, so it is very difficult to write different SQL statements and combine the results. I came up with following simple solution. It was tested on Oracle 8.1.7 and 9i.

SELECT a.plant_code,
( SELECT plant_code, count(1) no_of_recs FROM po_lines GROUP BY plant_code )
( SELECT plant_code, count(1) po_number FROM po_lines where po_number IS
NULL GROUP BY plant_code ) B,
( SELECT plant_code, count(1) unspsc_code FROM po_lines where unspsc_code IS
NULL GROUP BY plant_code ) C,
( SELECT plant_code, count(1) commodity_code FROM po_lines where
commodity_code IS NULL GROUP BY plant_code ) D
WHERE a.plant_code = b.plant_code (+)
   AND a.plant_code = c.plant_code (+)
   AND a.plant_code = d.plant_code (+)
ORDER BY a.plant_code
You can use following SQL to generate a FROM clause (which reduces typing). This is real helpful when you have lot of columns in a table:
select '( SELECT plant_code, count(1) '||lower(column_name) ||' FROM
po_lines where '|| lower(column_name) ||
' IS NULL GROUP BY plant_code'||' ) ' ||chr(column_id + 65) || ', '
from user_tab_columns where table_name = 'PO_LINES'
order by column_idp;
You can cut and paste the above SQL's output into a FROM clause. I am now able to give the project manager the number of rows with NULLs in each table within few minutes.

For More Information

  • Feedback: E-mail the editor with your thoughts about this tip.
  • More tips: Hundreds of free Oracle tips and scripts.
  • Tip contest: Have an Oracle tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize -- submit your tip today!
  • Ask the Experts: Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
  • Forums: Ask your technical Oracle questions--or help out your peers by answering them--in our active forums.
  • Best Web Links: Oracle tips, tutorials, and scripts from around the Web.

Dig Deeper on Oracle and SQL

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.