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..)
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
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`);
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