🧚 주목! Beekeeper Studio는 빠르고 현대적이며 오픈 소스 데이터베이스 GUI입니다 다운로드
April 29, 2024 작성자: 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.

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.

Beekeeper Studio는 무료 & 오픈 소스 데이터베이스 GUI입니다

제가 사용해 본 최고의 SQL 쿼리 & 편집기 도구입니다. 데이터베이스 관리에 필요한 모든 것을 제공합니다. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio는 빠르고 직관적이며 사용하기 쉽습니다. Beekeeper는 많은 데이터베이스를 지원하며 Windows, Mac, Linux에서 훌륭하게 작동합니다.

Beekeeper의 Linux 버전은 100% 완전한 기능을 갖추고 있으며, 기능 타협이 없습니다.

사용자들이 Beekeeper Studio에 대해 말하는 것

★★★★★
"Beekeeper Studio는 제 예전 SQL 워크플로를 완전히 대체했습니다. 빠르고 직관적이며 데이터베이스 작업을 다시 즐겁게 만들어 줍니다."
— Alex K., 데이터베이스 개발자
★★★★★
"많은 데이터베이스 GUI를 사용해 봤지만, Beekeeper는 기능과 단순함 사이의 완벽한 균형을 찾았습니다. 그냥 작동합니다."
— Sarah M., 풀스택 엔지니어

SQL 워크플로를 개선할 준비가 되셨나요?

download 무료 다운로드