How to Subtract one Value From Another in SQL
Database:
Operators:
Table of Contents
Problem:
You want to subtract one numeric value from another in SQL.
Example:
As an example, let’s take the table revenue
. It stores information on income and expenses for different months. The table has 4 columns: year
, month
, income
, and expenses
.
year | month | income | expenses |
---|---|---|---|
2022 | June | 8600 | 4300 |
2022 | July | 5500 | 4500 |
2022 | August | 9000 | 7300 |
2022 | September | 12000 | 8000 |
Let’s calculate the profit for each month. To get the profit value, you need to subtract the expenses from the income.
Solution:
To subtract the expenses from the income, take the two columns and subtract one from another using the standard - subtraction operator. Let’s see the differences between income and expenses for the months included in the table:
SELECT year, month, income - expenses as profit FROM revenue; Here’s the result:
year | month | profit |
---|---|---|
2022 | June | 4300 |
2022 | July | 1000 |
2022 | August | 1700 |
2022 | September | 4000 |
Discussion:
The use of subtraction in SQL is not limited to SELECT
. It is allowed in other parts of the query, e.g., in WHERE
:
SELECT year, month FROM revenue WHERE income - expenses > 3000;