February 14, 2024 By Matthew Rathbone

Introduction

Subtracting values is a fundamental operation in any SQL database, including SQLite. Understanding how to perform subtraction and utilize it in your queries can significantly enhance data manipulation and analysis. This guide aims to demystify subtraction in SQLite, providing clear examples and explaining the logic behind them. Whether you’re refining financial data, calculating time differences, or just crunching numbers, mastering subtraction in SQLite will elevate your SQL game.

Basics of Subtraction in SQLite

SQLite, like other SQL databases, supports basic arithmetic operations: addition, subtraction, multiplication, and division. Using the - operator, you can easily subtract one value from another.

Simple Subtraction

-- Subtracting two numbers
SELECT 10 - 5 AS difference;

Expected Output

difference
----------
5

Subtracting Columns

In a more practical scenario, you might want to subtract one column from another. This is straightforward in SQLite.

-- Assuming a table 'financials' with columns 'revenue' and 'expenses'
SELECT revenue, expenses, revenue - expenses AS profit FROM financials;

This query calculates the profit by subtracting expenses from revenue for each row in the financials table.

Advanced Subtraction Techniques

Subtraction isn’t limited to just simple arithmetic. It can be part of more complex expressions, including those involving dates and times.

Working with Dates

SQLite allows you to subtract one date from another to find the difference in days. However, this requires using the julianday function, which converts a date into a Julian day number. Subtracting these numbers yields the difference in days.

CREATE TABLE events (
    title TEXT,
    start DATE,
    end DATE);
INSERT INTO events VALUES('Tech Conference', '2024-02-28', '2024-03-02');

To find the event’s duration:

SELECT title, julianday(end) - julianday(start) AS 'duration' 
FROM events;

Expected Output:

Tech Conference   2.0

Conditional Subtraction with CASE

You can perform conditional subtraction using the CASE statement. This is useful for more nuanced calculations that depend on certain conditions.

-- Assuming a table 'orders' with columns 'quantity' and 'discount_applied'
SELECT quantity, discount_applied,
       CASE
           WHEN discount_applied THEN quantity - 1
           ELSE quantity
       END AS final_quantity
FROM orders;

This example deducts one from the quantity if a discount was applied, showcasing how to conditionally subtract values.

Practical Use Cases

Calculating Age

One common use case is calculating someone’s age based on their birthdate.

SELECT name, birthdate,
       (strftime('%Y', 'now') - strftime('%Y', birthdate)) - (strftime('%m-%d', 'now') < strftime('%m-%d', birthdate))
       AS age
FROM people;

This query calculates the age by subtracting the birth year from the current year and adjusting if today is before the person’s birthday this year.

Financial Reporting

Subtraction is key in financial reporting, for example, to calculate the monthly change in expenses.

-- Assuming a table 'monthly_expenses' with columns 'month' and 'amount'
SELECT month,
       amount - LAG(amount) OVER (ORDER BY month) AS monthly_change
FROM monthly_expenses;

This example uses the LAG window function to subtract the previous month’s expenses from the current month’s, showcasing the power of subtraction in financial analysis.

Conclusion

Subtraction in SQLite is a versatile tool in your SQL toolkit. From basic arithmetic to complex conditional logic and date manipulations, understanding how to use subtraction effectively can unlock deeper insights into your data. Remember, practice makes perfect. Experiment with these examples and incorporate subtraction into your SQL queries to see how it can improve your data analysis and reporting capabilities.

Beekeeper Studio Is A Free & Open Source Database GUI

Best SQL query & editor tool I have ever used. It provides everything I need to manage my database. - ⭐⭐⭐⭐⭐ Mit

Beekeeper Studio is fast, intuitive, and easy to use. Beekeeper supports loads of databases, and works great on Windows, Mac and Linux.

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