Re: alternative to select count(*) : do i need to ?

From: Thomas Kyte <tkyte_at_us.oracle.com>
Date: Fri, 17 Dec 1999 14:49:47 -0500
Message-ID: <vu3l5soqgdve2a18mp48pi6pmqvu066g61_at_4ax.com>


A copy of this was sent to legarema_at_uqtr.uquebec.ca (if that email address didn't require changing) On Fri, 17 Dec 1999 11:02:28 -0500, you wrote:

>Hi all,
>
>I am mostly programming in Pro*C 8.0.5.0.0 with an
>oracle 8.0.5 database (on aix 4.2.1.0). I have read
>some posts on this forum and on some web pages that
>are saying that it's bad programming to do a :
>
>select count(*) from mytable where criteria
>
>Most of the time I use count(*) to know if there is
>zero, one or more than one record matching my criteria.
>
>Is it really "bad programming" ?

probably

>If yes, is why ?

you are executing lots of un-necessary code and doing lots of work you don't need to.

>What are the alternatives ?

Array fetch. the very first fetch will tell you if you have 0, 1 or more rows. Additionally, array fetching will make your program do less network round trips (and be faster).

Eg:

static void process2()
{
EXEC SQL BEGIN DECLARE SECTION;
    int empno[5];
EXEC SQL END DECLARE SECTION;

    int     i;
    int     last_row_cnt;
    int     sqlCode;


    for( last_row_cnt = 0;
         sqlca.sqlcode == 0;
         last_row_cnt = sqlca.sqlerrd[2] )
    {
        EXEC SQL WHENEVER SQLERROR DO sqlerror_hard();
        EXEC SQL SELECT EMPNO INTO :empno FROM EMP;

        printf( "===========\nSQLCODE = %d\n", sqlca.sqlcode );

        printf( "Last Row Cnt = %d, sqlca.sqlerrd[2] = %d\n",
                 last_row_cnt, sqlca.sqlerrd[2] );

        printf( "that means we got %d rows this time around\n\n",
                 sqlca.sqlerrd[2]-last_row_cnt );

        for( i = 0; i < sqlca.sqlerrd[2]-last_row_cnt; i++ )
        {
            printf( "empno[%d] = %d\n", last_row_cnt+i, empno[i] );
        }

    }

    printf( "Done\n" );
}

>
>Thanks a lot,

-- 
See http://osi.oracle.com/~tkyte/ for my columns 'Digging-in to Oracle8i'...
Current article is "Part I of V, Autonomous Transactions" updated June 21'st
 
Thomas Kyte                   tkyte_at_us.oracle.com
Oracle Service Industries     Reston, VA   USA

Opinions are mine and do not necessarily reflect those of Oracle Corporation
Received on Fri Dec 17 1999 - 20:49:47 CET

Original text of this message