[Solved] Arithmetic operation performance in SQL
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Arithmetic operation performance in SQL

Say I have a table with prices and different percents, and I need to calculate the sum of the percentage.

And I run this query,

SELECT 
    i.user_id,
    i.payment_type,
    SUM(id.price),
    SUM(ROUND(id.price / (1 + (id.some_percent / 100)))) AS subtotal,
    SUM(ROUND(id.price - (id.crc_price / (1 + (id.some_percent / 100))))) AS some_percent_sum,
    SUM(ROUND((id.price / (1 + (id.some_percent / 100))) * (id.another_percent / 100))) AS another_percent_sum
FROM
    invoice i
        INNER JOIN
    invoice_details id ON i.invoice_id = id.invoice_id
GROUP BY i.user_id , payment_type

Will this query affect my SQL performance? Assuming all my index are optimized.

Or is it better to return the raw data and do the calculations in the server (whatever language c#, java, etc..)

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `invoice` ADD INDEX `invoice_idx_user_id_payment_type` (`user_id`,`payment_type`);
ALTER TABLE `invoice_details` ADD INDEX `invoice_details_idx_invoice_id` (`invoice_id`);
The optimized query:
SELECT
        i.user_id,
        i.payment_type,
        SUM(id.price),
        SUM(ROUND(id.price / (1 + (id.some_percent / 100)))) AS subtotal,
        SUM(ROUND(id.price - (id.crc_price / (1 + (id.some_percent / 100))))) AS some_percent_sum,
        SUM(ROUND((id.price / (1 + (id.some_percent / 100))) * (id.another_percent / 100))) AS another_percent_sum 
    FROM
        invoice i 
    INNER JOIN
        invoice_details id 
            ON i.invoice_id = id.invoice_id 
    GROUP BY
        i.user_id,
        i.payment_type 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.