0

This is the table:

dt VARCHAR(65)
ct VARCHAR(65)
amount INT

This is the query:

SELECT SUM(CASE WHEN dt='peter' THEN amount ELSE -amount END) 
FROM receipt WHERE dt='peter' OR ct='peter'

I have 800k records in the table. And I have indexes on dt, ct, amount, and ct,dt. At the moment this query takes over 5 minutes (!).

1
  • 4
    Show us the execution plan (ideally as explain analyze) Commented Sep 11, 2013 at 11:21

1 Answer 1

2

You can do

SELECT SUM(s) AS ss
FROM (SELECT SUM(amount) AS s
      FROM receipt
      WHERE dt = 'peter'
      UNION
      SELECT -SUM(amount)
      FROM receipt
      WHERE dt = 'peter')

This query should run faster than your original one. Otherwise you should normalize the dt/ct columns to use joins for better performance

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.