Reg: concept of COUNT and NULLs -

Hi Experts,
I have a simple conceptual doubt regarding COUNT and NULLs.
Even I have experimented and can justify the behaviour, just need to confirm once with guru's and experts over here.
Workout:
CREATE TABLE test_x1
AS
SELECT 1 col1, 'a' col2, 'a1' col3 FROM dual UNION ALL
SELECT 2 col1, 'a' col2, 'a1' col3 FROM dual UNION ALL
SELECT 3 col1, 'a' col2, 'a1' col3 FROM dual UNION ALL
SELECT 4 col1, 'a' col2, 'a1' col3 FROM dual UNION ALL
SELECT 5 col1, 'a' col2, 'a1' col3 FROM dual UNION ALL
SELECT 6 col1, 'a' col2, NULL col3 FROM dual UNION ALL
SELECT NULL col1, NULL col2, NULL col3 FROM dual UNION ALL
SELECT 8 col1, 'a' col2, NULL col3 FROM dual;
SELECT
  Count(*),
  Count(col1),
  Count(col2),
  Count(col3)
FROM test_x1;
COUNT(*) COUNT(COL1) COUNT(COL2) COUNT(COL3)
       8           7           7           5
My justification:
COUNT(*) - It counts for physical *rowid* ,and doesn't bother to check if data in the columns is it NULL or anything else.
Whereas, COUNT(<column>) - just scans/counts the known values and NOT NULLs.
Is the above correct? Please advise me on this.
-- Ranit

it's documented: http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions039.htm#SQLRF00624
If you specify expr, then COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr.
If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls. COUNT never returns null.
So the answer is: yes.

Similar Messages

  • Difference between Null in c and Null in Oracle

    Hi,
    Can any one tell me the difference between NULL in C language and NULL in Oracle
    Rds,
    Naga

    > Null is some garvage value in oracle.
    Not sure what you mean.
    AFAIK and not being a C programmer myself, isn't null CHR(0) in C? I'm not sure the two concepts (SQL null and C null) have anything in common.

  • Difference between empty plsql record and null plsql record

    Hi there,
    I am kinda getting confused with empty plsql record and null plsql record.
    How do I assign plsql record to be empty and to be null?
    create type emp_obj as object (enum number, ename varchar2);
    CREATE OR REPLACE TYPE emp_type AS TABLE OF emp_obj;
    Thanks

    First of all, do not use term PL/SQL record in this context. Record type in PL/SQL is completely different from object type. Secondly, there are 2 states of a nested table:
    1. Unintialized:
    SQL> create or replace
      2    type emp_obj_type as object(enum number, ename varchar2(10));
      3  /
    Type created.
    SQL> create or replace
      2    type emp_tbl_type as table of emp_obj_type
      3  /
    Type created.
    SQL> declare
      2      v_emp_tbl emp_tbl_type;
      3  begin
      4      v_emp_tbl.extend;
      5  end;
      6  /
    declare
    ERROR at line 1:
    ORA-06531: Reference to uninitialized collection
    ORA-06512: at line 4
    SQL> 2 Empty:
    SQL> set serveroutput on
    SQL> declare
      2      v_emp_tbl emp_tbl_type := emp_tbl_type();
      3  begin
      4      dbms_output.put_line('Nested table v_emp_tbl has ' || v_emp_tbl.count || ' element(s).');
      5  end;
      6  /
    Nested table v_emp_tbl has 0 element(s).
    PL/SQL procedure successfully completed.
    SQL> NULL aplies to nested table element, not to nested table itself:
    SQL> declare
      2      v_emp_tbl emp_tbl_type := emp_tbl_type();
      3  begin
      4      v_emp_tbl.extend;
      5      if v_emp_tbl(1) is null
      6        then
      7          dbms_output.put_line('Nested table v_emp_tbl first element is NULL.');
      8      end if;
      9  end;
    10  /
    Nested table v_emp_tbl first element is NULL.
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Question to modify a for loop to put a counter and parametrize it

    I have a FOR loop which is part of a PROCEDURE, the loop currently commits records for a large group of network providers. I need to modify it put a counter and commit for every 100 rows and make the number of rows of 100 parametrized. Any idea how this can be accomplished?
    FOR cur_netrec IN cur_network_mc (curproc.mpicontractid)
                LOOP
                   v_effectivedate := NULL;
                   v_terminationdate := NULL;
                   v_delegated := 'N';
                   v_individual := 'N';
                   v_credential := NULL;
                   FOR cur_conrec
                   IN cur_cont (cur_netrec.providerid, cur_netrec.mpinetworkcode)
                   LOOP
                      IF cur_conrec.effdate IS NOT NULL
                      THEN
                         v_effectivedate :=
                            LEAST (cur_conrec.effdate,
                                   NVL (v_effectivedate, '31-DEC-9999'));
                      END IF;
                   END LOOP;
                   IF cur_netrec.mpinetworkproviderid IS NULL
                   THEN
                      INSERT INTO mpi_provider.mpinetworkprovider (
                                                                      mpinetworkproviderid,
                                                                      providerid,
                                                                      mpinetworkcode,
                                                                      providernetworkcode,
                                                                      effectivedate,
                                                                      terminationdate,
                                                                      credentialingtypecode,
                                                                      createdby,
                                                                      creationdate,
                                                                      modifiedby,
                                                                      modificationdate
                        VALUES   (
                                     seq_mpinetworkprovider.NEXTVAL,
                                     cur_netrec.providerid,
                                     cur_netrec.mpinetworkcode,
                                     (SELECT   otherid
                                        FROM   mpi_provider.mpiprovider
                                       WHERE   providerid = cur_netrec.providerid),
                                     NVL (cur_netrec.effectivedateoverride,
                                          v_effectivedate),
                                     NVL (cur_netrec.terminationdateoverride,
                                          v_terminationdate),
                                     v_credential,
                                     USER,
                                     TRUNC (SYSDATE),
                                     USER,
                                     TRUNC (SYSDATE)
                   ELSE
                      UPDATE   mpinetworkprovider
                         SET   effectivedate =
                                  NVL (cur_netrec.effectivedateoverride,
                                       v_effectivedate),
                               terminationdate =
                                  NVL (cur_netrec.terminationdateoverride,
                                       v_terminationdate),
                               credentialingtypecode = v_credential,
                               modificationdate = TRUNC (SYSDATE),
                               modifiedby = USER
                       WHERE   providerid = cur_netrec.providerid
                               AND mpinetworkcode = cur_netrec.mpinetworkcode;
                   END IF;
                   --update when contract credential type code change
                   UPDATE   mpi_provider.person prs
                      SET   prs.credentialingtypecode =
                               (SELECT   DECODE (MIN (credtype),
                                                 1, 'DELEGNCQA',
                                                 2, 'DELEGNETEX',
                                                 3, 'DELEGATED',
                                                 4, 'NONDELEG',
                                                 5, 'INDIVIDUAL',
                                                 6, 'NONDENETEX',
                                                 'NONE')
                                            AS personcredentialingtypecode
                                  FROM   (SELECT   DECODE (
                                                      c.credentialingtypecode,
                                                      'DELEGNCQA',
                                                      1,
                                                      'DELEGNETEX',
                                                      2,
                                                      'DELEGATED',
                                                      3,
                                                      'NONDELEG',
                                                      4,
                                                      'INDIVIDUAL',
                                                      5,
                                                      'NONDENETEX',
                                                      6,
                                                      7
                                                      AS credtype
                                            FROM   mpi_provider.mpicontractprovider cp,
                                                   mpi_provider.mpicontract c
                                           WHERE   c.mpicontractid =
                                                      cp.mpicontractid
                                                   AND cp.providerid =
                                                         cur_netrec.providerid
                                                   AND cp.terminationdate >
                                                         SYSDATE))
                    WHERE   prs.providerid = cur_netrec.providerid;
                   COMMIT;          
                END LOOP;

    This piece could be accomplished with a MERGE, too
                   IF cur_netrec.mpinetworkproviderid IS NULL
                   THEN
                      INSERT INTO mpi_provider.mpinetworkprovider (
                                                                      mpinetworkproviderid,
                                                                      providerid,
                                                                      mpinetworkcode,
                                                                      providernetworkcode,
                                                                      effectivedate,
                                                                      terminationdate,
                                                                      credentialingtypecode,
                                                                      createdby,
                                                                      creationdate,
                                                                      modifiedby,
                                                                      modificationdate
                        VALUES   (
                                     seq_mpinetworkprovider.NEXTVAL,
                                     cur_netrec.providerid,
                                     cur_netrec.mpinetworkcode,
                                     (SELECT   otherid
                                        FROM   mpi_provider.mpiprovider
                                       WHERE   providerid = cur_netrec.providerid),
                                     NVL (cur_netrec.effectivedateoverride,
                                          v_effectivedate),
                                     NVL (cur_netrec.terminationdateoverride,
                                          v_terminationdate),
                                     v_credential,
                                     USER,
                                     TRUNC (SYSDATE),
                                     USER,
                                     TRUNC (SYSDATE)
                   ELSE
                      UPDATE   mpinetworkprovider
                         SET   effectivedate =
                                  NVL (cur_netrec.effectivedateoverride,
                                       v_effectivedate),
                               terminationdate =
                                  NVL (cur_netrec.terminationdateoverride,
                                       v_terminationdate),
                               credentialingtypecode = v_credential,
                               modificationdate = TRUNC (SYSDATE),
                               modifiedby = USER
                       WHERE   providerid = cur_netrec.providerid
                               AND mpinetworkcode = cur_netrec.mpinetworkcode;
                   END IF;
                   --update when contract credential type code change
                   UPDATE   mpi_provider.person prs
                      SET   prs.credentialingtypecode =
                               (SELECT   DECODE (MIN (credtype),
                                                 1, 'DELEGNCQA',
                                                 2, 'DELEGNETEX',
                                                 3, 'DELEGATED',
                                                 4, 'NONDELEG',
                                                 5, 'INDIVIDUAL',
                                                 6, 'NONDENETEX',
                                                 'NONE')
                                            AS personcredentialingtypecode
                                  FROM   (SELECT   DECODE (
                                                      c.credentialingtypecode,
                                                      'DELEGNCQA',
                                                      1,
                                                      'DELEGNETEX',
                                                      2,
                                                      'DELEGATED',
                                                      3,
                                                      'NONDELEG',
                                                      4,
                                                      'INDIVIDUAL',
                                                      5,
                                                      'NONDENETEX',
                                                      6,
                                                      7
                                                      AS credtype
                                            FROM   mpi_provider.mpicontractprovider cp,
                                                   mpi_provider.mpicontract c
                                           WHERE   c.mpicontractid =
                                                      cp.mpicontractid
                                                   AND cp.providerid =
                                                         cur_netrec.providerid
                                                   AND cp.terminationdate >
                                                         SYSDATE))
                    WHERE   prs.providerid = cur_netrec.providerid;

  • Count of NULL field from SQL Server

    Hi All,
    OBIEE 11g
    I have a requirement to count the number of rows from a table in SQL Server that has NULL values in that particular field. In the BMM I have placed a metric called Total Count and the aggregation for this is Count. The case statement I have in the BMM is as follows.
    CASE <FIELD TO COUNT>
    WHEN NULL THEN 1
    WHEN ' ' THEN 1
    ELSE 0
    I am not getting the correct results for this count.

    Try this
    sum(
    CASE WHEN COL is null or COL =' ' or COL ='' THEN 1 ELSE 0 END)
    If you count 0 also counting.
    Pls mark as correct/helpful if helps

  • Counting non null values

    I have a column of data and there are values and nulls how would I count just the values on a summary?
    Everything I have tried give me the total number of rows not the non null values.....
    tia
    Rose

    no you did not say something wrong -- but when we included a case statement for another field in the sql ---
    when we referenced the new field and tried to sum it in bi publisher gave us a 'Na' don't know why......
    Rose

  • Check count and then do some work

    Hi,
    I have a table with 10 million records. I want to check whether a value of a specific column is present or not. If the count is greather than 0, then I want to do some task and if it is 0, then I want to do some other task.
    Could you please tell me what is the best way to do?
    What I am doing now is: I am checking the count using count(*) and then checking the value whether that is greater than 0 or =0 and then based on the value I am doing different task.
    But count(*) is slow for this big table.
    So, please let me know the best possible way to do this.

    declare
      value_exists number;
    begin
      select count(*)
      into   value_exists
      from   my_table
      where  my_column = 'ABC' and
             rownum = 1;
      if value_exists = 1 then
      elsif value_exists = 0 then
      else raise_application_error(-20001,'Bad value for value_exists of '||coalesce(to_char(value_exists),'NULL'));
      end if;
    end;

  • Need to display count and report both by using single Query

    Hi All,
    I got any requirement in that i need to display count and report both.
    Like
    Count os Unassigned=20
    Count of Assined=23
    Sr   name     summary        etc ......
    1     dssss        sdsds         dsds
    2     sdada       sdsd          sdsds
    3     dadad       afds          sdada    And the problem is ,My Application is providing the single window where i can put a single query
    so pls help me with this

    I think you need to do it like this:
    WITH x AS (
        SELECT DECODE(name,NULL,0,1) AS ind, COUNT(*) AS counter FROM your_table
        GROUP BY DECODE(name,NULL,0,1)
        UNION SELECT 1,0 FROM dual
        UNION SELECT 0,0 FROM dual)
    SELECT DECODE(ind,0,'Count os Unassigned=','Count of Assined=') ||
           TO_CHAR(SUM(counter)) FROM x GROUP BY ind;Replace your_table with whatever your table is called.

  • Difference count(*) and count(1)

    Is there any difference between count(*) and count(1)
    when write select count(*) from emp
    and select count(1) from emp
    output of both query are same plz tell me the difference
    thnks

    Just as a side note. Count does behave differently if you count by a column.
    ex.
    select count(*) from perf_results;
       COUNT(*)
           3222
    select count(fy_year) from perf_results;
    COUNT(FY_YEAR)
              3207If a column has a null value it will not be counted

  • What is the difference between partition-count and the number of caches?

    What is the difference between partition-count and the number of caches in Coherence? Are they same?

    Those are totally orthogonal concepts.
    For more, look at this thread where I answered your other related questions and explain this, too:
    Where can I find the accurate definitions of these terms?
    Best regards,
    Robert

  • Counter and sessionid

    hello, i'm programming a web applications.
    It's two or three forms together sending and receiving data from a session using sessionid.
    I'd like to know how to make, once fielded, my data textfield persistent when changing from one form to another.
    I was thinking to make a counter and if the counter is changing take my data from the session and refill the textboxes.
    I don't know how to know if a counter isIncrementing.
    Someone can help me ?

    Depends on how you are coming back to the page.
    If you have left the page but are coming back to it later then the information from the form has been stored in the session. Probably a bean has been created to hold all of the form field data, then the bean is populated from the request and then stored in the session.
    When you return to the jsp with th eform it checks to see if there is a bean stored in the session. If it finds one it retrieves it and uses the data stored in the bean to b populate the form.
    In servlet:
    MyBean myBean = new MyBean();
    myBean.textField = request.getParameter("testField1");
    session.setAttribute("MyBean", myBean);
    In JSP:
    MyBean myBean = (MyBean)session.getAttribute("MyBean");
    <form>
    <% if (myBean == null) { %>
         <input type="textfield" name="textField1" value="" >
    <% } else { %>
         <input type="textfield" name="textField1" value="<%= myBean.getTextField() %>">
    <% } %>This is not the best way to do this but just an example of how it could be done.

  • Difference between Null and null?

    What is the difference between null and NULL?
    When is each used?
    Thanks,

    veryConfused wrote:
    There is a null in java, but no NULL. null means no value. However, when assigning value, the following is different:Although the empty String has no special role. Null means, the referential type is not assigned (doesn't refer) to a specific object. The empty String is just another object though, so seeing it or pointing it out as something special when it actually isn't at all (no more special than new Integer(0) or new Object[0]) just adds to the confusion.

  • How to differentiate the EMPTY Records and Null Values in DSO

    Hello....how is everyone here?? Ehehehe!
    I try to load some data from the flat file which contains some EMPTY data and Null Values for the records. The data type for the InfoObjects of the fields "Quantity" is "number". The sample data from the flat file (CSV) are as below:
    Food              Quantity
    Hamburger  -       12
    Cheese        -       0
    Vegetable      -               (Empty)
    When I try to load the above sample data to the DSO, I get the results of the data as follow:
    Food              Quantity
    Hamburger     - 12.000
    Cheese           -  0.000
    Vegetable         - 0.000
    In this case, how can the user differentiate whether the records is contain empty value of null values in DSO? This is kinda of hard to differentiate the both scenarios above. Is there any way to differentiate the scenarios described here?
    Thanks alot =)

    Hi Fluffy,
    It depends on the initial values of the data type
    The inital values For quantity/Currency/ Numbers it takes spaces as 0
    for char it is SPACE
    We cannot differeniate between space and null values.
    IF you have to force this then define quantity as char and load the data. we will not have units and aggregation in this case.
    Hope this helps.
    PV

  • How to force simple tags and null attributes to appear when using SQL/XML?

    Hello everybody:
    I'm developing a non-schema based XMLType view.
    When the XML document is generated, i noticed two things I need to manage in order to achieve the desired result:
    1. Oracle generates a <tag></tag> pair for each XMLELEMENT defined; in my case, some tags need to appear as <tag/>... how do I do? Is it possible when using schema based XMLType views? Is it possible while using a non-schema approach?
    2. When using XMLATTRIBUTE('' AS "attribute") or XMLATTRIBUTE(NULL AS "attribute"), no one attribute with label "attribute" and null value appears at the output; how do I force to Oracle DB to render those attributes which are with no values (needed to render those attributes as another parsing code will await for all the items)?
    3. Some tip about how to route the output to an XML text disk file will be appreciated.
    Thanks in advance.
    Edited by: Enyix on 26/02/2012 11:21 PM
    Edited by: Enyix on 26/02/2012 11:22 PM

    Hello odie_63, thanks for your reply:
    Reasons why needed single tags are these two next: Needed to generate a single XML file from 50,000,000 rows, where the XML ouput matches not only row data but another default values for another elements and attributes (not from database but using strings and types with default values); by using start and end tag, the generated file is as much twice bigger than using single tags; second, needed a very precise presentation for all the document.
    For generating that document, currently focus is based on using a batch process relying on Spring Batch with using a single JDBC query where a join happens between two tables. From my point of view, that approach uses: database resources, network resources, disk resources, and processing resources, including the price of making the join, sending to network, creating objects, validating, and making the file (Expending too much time generating that XML file). That processs currently is in development.
    I think possibly another approach is delegating the complete generation of that file to the database using its XML capabilities. My current approach following your recomendations is to generate a clob where I will put all the XML and putting it into a table. It leads me to another issues: Considering limitations on memory, processing and disk space, needed to append a single row-as-xml into the clob as soon as possible, and putting the clob inside the field as soon as possible, or putting the clob inside the field, and appending into it as the data is generated; so How do I manage the process in order to achieve that goals?. Seen these issues aren't related to my original question, so I'll open a new post. Any help will be apreciated.
    Thanks again in advance.

  • How to check empty string and null? Assign same value to multiple variables

    Hi,
    1.
    How do I check for empty string and null?
    in_value IN VARCHAR2
    2. Also how do I assign same value to multiple variables?
    var_one NUMBER := 0;
    var_two NUMBER := 0;
    var_one := var_two := 0; --- Gives an error
    Thanks

    MichaelS wrote:
    Not always: Beware of CHAR's:
    Bug 727361: ZERO-LENGTH STRING DOES NOT RETURN NULL WHEN USED WITH CHAR DATA TYPE IN PL/SQL:
    SQL> declare
      2    l_str1   char (10) := '';
      3    l_str2   char (10) := null;
      4  begin
      5  
      6    if l_str1 is null
      7    then
      8      dbms_output.put_line ('oh STR1 is null');
      9    elsif l_str1 is not null
    10    then
    11      dbms_output.put_line ('oh STR1 is NOT null');
    12    end if;
    13  
    14    if l_str2 is null
    15    then
    16      dbms_output.put_line ('oh STR2 is null');
    17    elsif l_str2 is not null
    18    then
    19      dbms_output.put_line ('oh STR2 is NOT null');
    20    end if;
    21  end;
    22  /
    oh STR1 is NOT null
    oh STR2 is null
    PL/SQL procedure successfully completed.
    SQL> alter session set events '10932 trace name context forever, level 16384';
    Session altered.
    SQL> declare
      2    l_str1   char (10) := '';
      3    l_str2   char (10) := null;
      4  begin
      5  
      6    if l_str1 is null
      7    then
      8      dbms_output.put_line ('oh STR1 is null');
      9    elsif l_str1 is not null
    10    then
    11      dbms_output.put_line ('oh STR1 is NOT null');
    12    end if;
    13  
    14    if l_str2 is null
    15    then
    16      dbms_output.put_line ('oh STR2 is null');
    17    elsif l_str2 is not null
    18    then
    19      dbms_output.put_line ('oh STR2 is NOT null');
    20    end if;
    21  end;
    22  /
    oh STR1 is null
    oh STR2 is null
    PL/SQL procedure successfully completed.
    SQL> SY.

Maybe you are looking for

  • Issues with subject line when moving emails to another folder

    Hi. For the past few months I've been having a problem moving groups of emails from my inbox to another created folder. When I move a group of emails to another folder the subject of all the emails swap with each other. The issue seems to be with the

  • Sending an Email with Excel Attachment from Local directory

    Hi, I have a requirement : I want to send an email with an attachment which is exist on local  directory and currently I am using cl_bcs classes Thanks, Moderator message: Welcome to SCN! Moderator message: please do more research before asking, show

  • How can get the SAP MDM downloaded from  SAP Marketplace?

    Hi Experts, I have tried to download the MDM from the below link - http://service.sap.com/swdc > SAP Software Distribution Center > Download > Installations and Upgrades > Entry by Application Group > SAP NetWeaver > SAP MDM > SAP NetWeaver MDM 7.1 B

  • Creating links to Word, PDF and Powerpoint files

    I need advice on how to create links to Word, Powerpoint and PDF files in my Captivate project.  How do I also make sure that when my file is published, those links can be accessed by the reader.  I am new to this process.  Thanks!

  • Will Apple ever consider expanding its keyboard on its mobile devises?

    Will Apple ever consider expanding its keyboard on its mobile devises? We are endlessly having to punch in our multiple-symbol passwords and constantly having to switch between keyboards is frustrating. I think it's a good idea.