Back to cookbooks list Articles Cookbook

How to Subtract one Value From Another in SQL

  • -

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.

yearmonthincomeexpenses
2022June86004300
2022July55004500
2022August90007300
2022September120008000

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:
yearmonthprofit
2022June4300
2022July1000
2022August1700
2022September4000

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;

Recommended courses:

Recommended articles:

See also: