Search code examples
sqlfirebirdfirebird2.5

How can I simplify two selects


Is it possible to simplify two selects, maybe into one as they add a bit of time when used in a stored Procedure and called many times?

/* Get Our OVER Spent Codes */
select SUM(Cmt.BALANCE_TD)
from CODES_MONTHLY_TABLE Cmt
WHERE (Cmt.id = :ip_id) and (Cmt.BALANCE_TD < 0) and ((Cmt.THEMONTH - 1) = :ip_currentmonth)
into :op_overspent_codes;

/* Get Our UNDER Spent Codes */
select SUM(Cmt.BALANCE_TD)
from CODES_MONTHLY_TABLE Cmt
WHERE (Cmt.id = :ip_id) and (Cmt.BALANCE_TD > 0) and ((Cmt.THEMONTH - 1) = :ip_currentmonth)
into :op_underspent_codes;

The table CODES_MONTHLY_TABLE is quite large and I have an index on the field Cmt.id.

These are input parameters:

  • :ip_id
  • :ip_currentmonth

Solution

  • Try

    select 
      SUM(case when (Cmt.BALANCE_TD < 0) then Cmt.BALANCE_TD else 0 end) ,
      SUM(case when (Cmt.BALANCE_TD > 0) then Cmt.BALANCE_TD else 0 end)
    from CODES_MONTHLY_TABLE Cmt
    WHERE (Cmt.id =  :ip_id) and (Cmt.THEMONTH  = (:ip_currentmonth - 1))
    INTO :op_overspent_codes,:op_underspent_codes;
    

    And index on (id, themonth) is better for this query performance.

    Upd1. Should be

    WHERE (Cmt.id =  :ip_id) and (Cmt.THEMONTH  = (:ip_currentmonth + 1))