Search code examples
performanceplsqlcursor

Performance of using cursor PLSQL


I have to get a count using a cursor. the basic cursor is

get *
from table

In here there are three types of data I want to get the count of.

sysdate < start_date
sysdate > startdate and sysdate < enddate
sysdate > enddate

I have 2 ways of doing this.

  1. Loop the above cursor and use a if condition to get the counts.

  2. Create 3 separate cursors with the conditions and directly get the count

As I have a lot of data what way would be good in perspective of performance ?


Solution

    1. Don't use a cursor at all.

    Use conditional aggregation. That's almost surely faster than any cursor based approach.

    SELECT count(CASE
                   WHEN sysdate < start_date THEN
                     1
                 END) count1,
           count(CASE
                   WHEN sysdate > startdate
                        AND sysdate < enddate THEN
                     1
                 END) count2,
           count(CASE
                   WHEN sysdate > enddate THEN
                     1
                 END) count3
           FROM elbat;