I am trying to execute following PL/SQL script in SQL Developer. The loop should return count of nulls but somehow everytime it is returning 0. set serveroutput on
DECLARE
--v_count number;
v_count_null number;
BEGIN
execute immediate 'select count(*) from SP_MOSAIX' into v_count;
FOR i in (select column_name from all_tab_COLUMNS where table_name = 'SP_MOSAIX')
LOOP
select count(*) into v_count_null from SP_MOSAIX where i.column_name IS NULL ;
dbms_output.put_line(v_count_null);
END LOOP;
END;
So when I run this, following output is what i get:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
But if I manually execute the query subsituting column_name I get the result.
select count(*) into v_count_null from SP_MOSAIX where i.column_name IS NULL;
Can anybody help on this?
There are a couple of things going on here that you need to be aware of. Firstly, as you allude to, your COUNT query is executing using the value of i.column_name, which is never NULL.
Secondly,
COUNT(*)
returns the number of rows that match yourWHERE
clause condition, regardless ofNULL
values. If you want to count how manyNOT NULL
values there are in a particular column, you mustCOUNT
values in that column explicitly.Please see the following example (SQL Fiddle):
Oracle 11g R2 Schema Setup:
Query 1:
Results:
As you can see,
COUNT(*)
always returns the number of rows present, but the others vary in results depending on whetherNULL
values are present in the specified column or not.You'll need to use
EXECUTE IMMEDIATE
to convert your column name into part of the query. Something like this might do the job:Query 2:
You need to use dynamic SQL, which will allow you to reference each column: