1

SQL syntax question about UPDATE. It would be much easier to ask the question by giving example below:

**Payments Table**

ID  user_id  payment_due   payment_made 
1      3        10.0           5.0
1      3        10.0           10.0
1      9        20.0           20.0



**Balance Table**

ID  user_id    current_balance 
1      3            ???
2      9            ???

Let say I would like to update the current balance for specific user. What would be the correct and efficient SQL syntax to add all payment dues and subtract it from all payment made for a specific user?

In this case, current_balance for user '3' is 5.0 and for user '9' is 0.0

3 Answers 3

2

How about:

select
   ID,
   user_id,
   (sum(payment_due) - sum(payment_made)) current_balance
from
   PaymentsTable

group by
   ID,
   user_id
Sign up to request clarification or add additional context in comments.

4 Comments

This might be the best approach. Don't keep a Balance table since the balance would constantly change. You could even turn this query into a view so that it behaves like the Balance table.
Or use a trigger to keep the data in sync.
as stated above don't keep a Balance table...storing a calculated field (current_balance) breaks the rules of normalization, use the query to get the data on the fly
Thanks all for the suggestions. I think it is best not to use current balance table
2

To update your table, use a sub-query:

UPDATE Balance_Table b
SET current_balance =
  ( SELECT SUM( payment_due - payment_made )
    FROM Payments_Table p
    WHERE p.user_id = b.user_id
  )

Think about the update-approach though. Your Balance_Table will be out of sync as soon as Payments_Table changes, so you might be better off with actually selecting data from there.

2 Comments

I suppose he could throw this UPDATE statement in a trigger on the Payments table. That would remove some of the discrepancy.
@cmptrgeekken: Using a trigger would be possible. If there are lots of records in Payments_Table but only few records change and results of Balance_Table are queried often, then this could be the right approach. Otherwise, just summing up Payments_Table would be the easier approach.
1

You need to use a subquery. Something like this should work:

UPDATE
    balance_table b
SET
    current_balance = (SELECT
            SUM(payment_due - payment_made)
        FROM
            payments_table p
        WHERE
            p.user_id = b.user_id)

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.