Search code examples
mysqlsqldatabasegroup-bysubquery

how to get difference of sum of values of acolumn of two different tables in mysql?


Table Income

+----+--------+-------------+
| Id | amount | description |
+----+--------+-------------+
| 26 |  10000 | Salary      |
| 27 |    500 | Test        |
+----+--------+-------------+

Second Expense

+----+--------+-------------+
| Id | amount | description |
+----+--------+-------------+
| 10 |   3000 | Rent        |
| 11 |   1500 | Test        |
+----+--------+-------------+

I Want the Output as

+-------+
| Total |
+-------+
|  6000 |
+-------+

Example:- Sum(amount) from Income - Sum(amount) from Expense;


Solution

  • Just substract the results of two aggregate scalar queries:

    select
        (select sum(amount) from income)
        - (select sum(amount) from expense) total
    

    Or in case any table may be empty or contain only null amounts:

    select
        (select coalesce(sum(amount), 0) from income)
        - (select coalesce(sum(amount), 0) from expense) total
    

    Note that, as commented by Strawberry, having a single table for income and expenses would probably be a better fit for your use case. You can either store expenses are negative amounts, or have a flag that indicates whether each row is an income or an expense.