Q:

Oracle PL/SQL FOR Loop Optimisation

Please can you assist me if possible, i need to optimize the below block of code if order to iterate the values quicker. see below statement :
for CONSULTANT_RECORD IN CONSULTANT_CURSOR LOOP /*Loop 2*/
VData := VData||crlf2||CONSULTANT_RECORD.USER_FIRSTNAME||'   '||CONSULTANT_RECORD.USER_SURNAME;

vTOT_LOG_CLOSED4USER := 0;
vAVERAGE_DAY := 0;
vTOT_DAYS := 0;
for x in 1..vlastday loop /*Loop 3*/
  select COUNT(DISTINCT LOG_NO) as "LOG_COUNT" INTO vLOG_COUNTER
    FROM DMS_CRM.TBL_DMS_SERVICE_REQUESTS_HIST
      WHERE LOG_STATUS = 'Resolved'
       AND TO_CHAR(HIST_DATE_TIME_STAMP, 'MONTH,YYYY') = TO_CHAR(SYSDATE, 'MONTH,YYYY')
       AND TO_CHAR(HIST_DATE_TIME_STAMP, 'DD') = lpad(to_char(x),2,'0')
       AND OWNER_USER_ID IS NOT NULL
       AND OWNER_USER_ID = CONSULTANT_RECORD.OWNER_USER_ID;

    end loop;
END LOOP;

The problem starts happening in the Comment Loop 3, bare in mind im developing over oracle app portal, so i cant run query optimization... my tables are indexed correctly as well (if anyone wants to comment on it).
Regards,
PS. No one has gotten back to me with their version of the code..........i am still struggling with this :-(

A:

I think the best loop is no loop at all (surely, if it's can be avoided). Assuming vlastday is a collection, you can do something like
select COUNT(DISTINCT LOG_NO) as "LOG_COUNT" 
FROM DMS_CRM.TBL_DMS_SERVICE_REQUESTS_HIST
INNER JOIN 
  (
    SELECT lpad(to_char(t.COLUMN_VALUE ),2,'0') as x 
    from table(vlastday)t
  )a ON (TO_CHAR(HIST_DATE_TIME_STAMP, 'DD') = a.x)
  WHERE LOG_STATUS = 'Resolved'
   AND TO_CHAR(HIST_DATE_TIME_STAMP, 'MONTH,YYYY') = TO_CHAR(SYSDATE, 'MONTH,YYYY')       
   AND OWNER_USER_ID IS NOT NULL
   AND OWNER_USER_ID = CONSULTANT_RECORD.OWNER_USER_ID
   GROUP BY a.x;

Then depends on your task, you need to either get rid of GROUP BY so you can select into, or declare a collection of numbers and BULK COLLECT into this variable. 
Also, I from what I see in the question, you can do pretty much the same for Loop2 so you won't have loops ...

