April 29, 2024 By Matthew Rathbone *

Introduction

Today we’ll be exploring how to perform subtraction in MySQL, a popular platform for managing relational databases. This tutorial will focus on subtraction in MySQL, covering a variety of scenarios from basic arithmetic operations to more complex use cases like calculating differences between rows or dates.

Please note: While many SQL concepts transfer across different database management systems, the examples provided in this article are designed specifically for MySQL.

A Database Manager That Is Modern, Fast, & Easy To Use

Tried a few tools. Beekeeper was the only one that I found that felt right. Most had a very 1990's feel to them - Allan

I built Beekeeper Studio because, like Allan, I wanted something more intuitive and modern than all the existing clunky apps I could find. My customers agree - they love using Beekeeper and they tell me every day! Give it a try, I bet you'll like it too.

Beekeeper's Linux version is 100% full-featured, no cut corners, no feature compromises.

Prerequisites

This tutorial assumes familiarity with MySQL. Ensure you have MySQL installed and access to a database where you can execute queries.

Section 1: Basic Arithmetic Operations in MySQL

Subtracting Numbers

MySQL supports basic arithmetic operators directly in the SELECT statement. Here’s how to perform a simple subtraction:

SELECT 15 - 7 AS difference;

Expected Output

+------------+
| difference |
+------------+
|          8 |
+------------+

This query subtracts 7 from 15 and labels the output as difference.

This is the simplest way of performing subtraction in MySQL. The ‘-‘ operator can be used for subtracting numbers directly, or to subtract numerical values stored in different columns of a table.

Subtracting Columns

To subtract two columns in a MySQL table, consider a table named financials with columns revenue and expenses.

SELECT revenue, expenses, (revenue - expenses) AS net_income FROM financials;

Expected Output:

+---------+----------+------------+
| revenue | expenses | net_income |
+---------+----------+------------+
| 10000   | 7000     | 3000       |
| 15000   | 12000    | 3000       |
+---------+----------+------------+

This query calculates the net income by subtracting expenses from revenue.

Section 2: Working with Dates

Subtracting Dates

In MySQL, subtracting dates can be used to calculate intervals, such as the number of days between two dates. For this, MySQL provides the DATEDIFF() function.

SELECT DATEDIFF('2023-12-31', '2023-01-01') AS days_difference;

Expected Output:

+-----------------+
| days_difference |
+-----------------+
|             364 |
+-----------------+

DATEDIFF() returns the number of days between two dates, which is particularly useful in financial and personnel calculations.

Subtracting Time Intervals

MySQL allows the subtraction of specific time intervals from dates using the DATE_SUB() function. Here’s how you can subtract 30 days from a specific date:

SELECT DATE_SUB('2023-12-31', INTERVAL 30 DAY) AS new_date;

Expected Output:

+------------+
| new_date   |
+------------+
| 2023-12-01 |
+------------+

Section 3: Advanced Subtraction Techniques

Calculating Running Totals

To demonstrate a running total calculation, which includes subtraction, let’s assume a ledger table named transactions with columns id, date, and amount.

SET @running_total := 0;

SELECT 
  id,
  date,
  amount,
  (@running_total := @running_total - amount) AS running_total
FROM transactions
ORDER BY date;

Expected Output:

+----+------------+--------+---------------+
| id | date       | amount | running_total |
+----+------------+--------+---------------+
|  1 | 2023-01-01 | 500    | -500          |
|  2 | 2023-01-02 | 150    | -650          |
+----+------------+--------+---------------+

This query uses a session variable to keep track of the running total, subtracting each transaction amount sequentially.

MySQL Subtraction with NULL Values

Remember, MySQL treats NULL as an unknown value. Include NULL in a subtraction operation, and the result will also be NULL. To solve this issue, you can use the COALESCE function.

SELECT COALESCE(column1, 0) - COALESCE(column2, 0) AS 'result' FROM table_name;

In instances where column1 or column2 contains NULL, the COALESCE function treats it as ‘0’, allowing the subtraction operation to still return an accurate result.

Conclusion

In SQL, not all operations are as straightforward as they seem, and subtraction is one of them. The best approach differs depending on whether you’re subtracting numbers, columns, date values or performing more advanced calculations.

Practice these scenarios on your own and experiment with other tables and column names.

Keep exploring, keep learning!

For more complex queries and real-world applications, continue exploring MySQL’s extensive documentation and functionality.