title: Optimize mysql if elseif and else logic
body: <p>This part of MySQL stored procedure works but is very slow. Is there any way to optimize it?</p>
  
  <pre><code>IF (p_regid &gt;0 AND p_submittedqueId&gt;0 AND p_saveresponse=True)  then  
          if not exists(select * from  responseok where regid=p_regid AND QID =p_submittedqueId and TestId=p_TestId) AND (p_COption!='' or p_responsetext!='') then 
  
              insert into  responseok (regid,TestId,QID,Response,ResponseText,timestamp)  
              select p_regid,p_testId,p_submittedqueId,p_COption,p_responsetext,now(3);
  
           elseif (p_responsetext ='' AND p_COption='') then 
              insert into responsehistory (regid,TestId,QID,timestamp)  
              select p_regid,p_testId,p_submittedqueId,now(3);
              delete from  responseok where regid =p_regid and QID =p_submittedQueId AND TestId=p_TestId;
           else 
              insert into responsehistory (regid,TestId,QID,timestamp)  
              select p_regid,p_testId,p_submittedqueId,now(3);
              delete from  responseok where regid =p_regid and QID =p_submittedQueId AND TestId=p_TestId;
              insert into  responseok (regid,TestId,QID,Response,ResponseText,timestamp)  
              select p_regid,p_testId,p_submittedqueId,p_COption,p_responsetext,now(3);
           end if;
  end if;
  </code></pre>
  
  <p>If I change the code to following, will it return the same results?</p>
  
  <pre><code>IF (p_regid &gt;0 AND p_submittedqueId&gt;0 AND p_saveresponse=True AND p_COption!='' or p_responsetext!='')  then  
          if not exists(select * from  responseok where regid=p_regid AND QID =p_submittedqueId and TestId=p_TestId) then
  
              insert into  responseok (regid,TestId,QID,Response,ResponseText,timestamp)  
              select p_regid,p_testId,p_submittedqueId,p_COption,p_responsetext,now(3);
  
           else 
              insert into responsehistory (regid,TestId,QID,timestamp)  
              select p_regid,p_testId,p_submittedqueId,now(3);
              delete from  responseok where regid =p_regid and QID =p_submittedQueId AND TestId=p_TestId;
          end if;
           else 
              insert into responsehistory (regid,TestId,QID,timestamp)  
              select p_regid,p_testId,p_submittedqueId,now(3);
              delete from  responseok where regid =p_regid and QID =p_submittedQueId AND TestId=p_TestId;
              insert into  responseok (regid,TestId,QID,Response,ResponseText,timestamp)  
              select p_regid,p_testId,p_submittedqueId,p_COption,p_responsetext,now(3);
           end if;
  </code></pre>
  
  <p>Will it improve the performance?</p>
  
  <p>Will it be faster if I change the logic "if not exists" to something like "select 1 into some_var"?</p>