Bird
Raised Fist0
MySQLquery~15 mins

DATE_ADD and DATE_SUB in MySQL - Deep Dive

Choose your learning style10 modes available
Overview - DATE_ADD and DATE_SUB
What is it?
DATE_ADD and DATE_SUB are functions in MySQL that let you add or subtract a specific amount of time to a date or datetime value. You can use them to change dates by days, months, years, hours, and more. These functions help you calculate new dates based on existing ones easily.
Why it matters
Without these functions, changing dates would be complicated and error-prone, especially when dealing with months or leap years. They solve the problem of date arithmetic, which is common in scheduling, reporting, and data analysis. Imagine trying to manually calculate a date 30 days from now every time you need it—these functions automate that safely and reliably.
Where it fits
Before learning DATE_ADD and DATE_SUB, you should understand basic date and time data types in MySQL. After mastering these functions, you can explore more complex date functions like TIMESTAMPDIFF or working with intervals in queries.
Mental Model
Core Idea
DATE_ADD and DATE_SUB let you move forward or backward on the calendar from a given date by adding or subtracting time intervals.
Think of it like...
It's like using a calendar where you flip pages forward or backward to find a new date based on how many days, months, or years you want to move.
┌─────────────┐       add 5 days       ┌─────────────┐
│ 2024-06-10  │ ─────────────────────> │ 2024-06-15  │
└─────────────┘                        └─────────────┘

┌─────────────┐      subtract 2 months   ┌─────────────┐
│ 2024-06-10  │ ─────────────────────> │ 2024-04-10  │
└─────────────┘                        └─────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Date and Time Types
🤔
Concept: Learn what date and datetime types are in MySQL and how they store information.
MySQL stores dates in formats like DATE (YYYY-MM-DD) and DATETIME (YYYY-MM-DD HH:MM:SS). These types let you save calendar dates and times in a standard way. For example, '2024-06-10' is a DATE, and '2024-06-10 14:30:00' is a DATETIME.
Result
You can store and recognize dates and times in your database correctly.
Understanding how dates are stored is essential before you can add or subtract time from them.
2
FoundationBasic Syntax of DATE_ADD and DATE_SUB
🤔
Concept: Learn the simple structure of these functions and how to write them.
DATE_ADD(date, INTERVAL value unit) adds time to a date. DATE_SUB(date, INTERVAL value unit) subtracts time from a date. Example: DATE_ADD('2024-06-10', INTERVAL 5 DAY) returns '2024-06-15'.
Result
You can write queries that change dates by adding or subtracting intervals.
Knowing the syntax lets you start manipulating dates immediately.
3
IntermediateUsing Different Time Units
🤔Before reading on: do you think you can add months and seconds with DATE_ADD? Commit to your answer.
Concept: DATE_ADD and DATE_SUB support many units like DAY, MONTH, YEAR, HOUR, MINUTE, SECOND.
You can add or subtract various units: - DAY: days - MONTH: months - YEAR: years - HOUR, MINUTE, SECOND: time parts Example: DATE_SUB('2024-06-10 14:30:00', INTERVAL 2 HOUR) returns '2024-06-10 12:30:00'.
Result
You can adjust dates and times precisely, not just whole days.
Understanding units expands your ability to handle both dates and times flexibly.
4
IntermediateCombining DATE_ADD with SELECT Queries
🤔Before reading on: do you think DATE_ADD can be used inside SELECT statements to change stored dates? Commit to your answer.
Concept: You can use DATE_ADD and DATE_SUB inside SELECT queries to calculate new dates on the fly.
Example: SELECT order_id, order_date, DATE_ADD(order_date, INTERVAL 7 DAY) AS delivery_date FROM orders; This shows the delivery date as 7 days after the order date.
Result
Your query results include calculated future or past dates without changing stored data.
Using these functions in queries helps you create dynamic reports and schedules.
5
AdvancedHandling Edge Cases Like Month Ends
🤔Before reading on: do you think adding 1 month to January 31 gives February 31? Commit to your answer.
Concept: DATE_ADD adjusts dates intelligently when adding months or years that land on invalid days.
Example: SELECT DATE_ADD('2024-01-31', INTERVAL 1 MONTH); Returns '2024-02-29' because February 31 does not exist, so it picks the last valid day. This prevents errors when adding months to dates near month ends.
Result
You get valid dates even when adding months to tricky dates like the 31st.
Knowing this prevents bugs and surprises when working with monthly intervals.
6
ExpertPerformance and Index Use with DATE_ADD
🤔Before reading on: do you think using DATE_ADD on indexed columns always uses indexes efficiently? Commit to your answer.
Concept: Using DATE_ADD in WHERE clauses can affect how MySQL uses indexes and query speed.
Example: SELECT * FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY); This can use indexes efficiently because the function is on the right side. But writing WHERE DATE_ADD(order_date, INTERVAL 7 DAY) >= CURDATE() may prevent index use. Understanding how to write queries affects performance.
Result
You write faster queries by knowing how DATE_ADD interacts with indexes.
Knowing query optimization with date functions is key for large databases.
Under the Hood
Internally, MySQL stores dates as numeric values representing year, month, day, and time parts. DATE_ADD and DATE_SUB convert the date to this internal format, add or subtract the specified interval, and then convert back to a readable date. When adding months or years, MySQL adjusts for invalid days by moving to the last valid day of the resulting month.
Why designed this way?
This design ensures date arithmetic is consistent and handles real-world calendar quirks like leap years and varying month lengths. Alternatives like manual string manipulation were error-prone and complex, so built-in functions provide a reliable, standardized approach.
┌───────────────┐
│ Input Date    │
│ '2024-01-31'  │
└──────┬────────┘
       │ Convert to internal numeric format
       ▼
┌───────────────┐
│ Internal Date │
│ representation│
└──────┬────────┘
       │ Add interval (e.g., 1 MONTH)
       ▼
┌───────────────┐
│ Adjust for    │
│ invalid days  │
│ (Feb 31 → 29) │
└──────┬────────┘
       │ Convert back to date string
       ▼
┌───────────────┐
│ Output Date   │
│ '2024-02-29'  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does DATE_ADD('2024-01-31', INTERVAL 1 MONTH) return '2024-02-31'? Commit yes or no.
Common Belief:Adding 1 month always just increases the month number, so January 31 plus 1 month is February 31.
Tap to reveal reality
Reality:MySQL adjusts invalid dates to the last valid day of the month, so it returns February 29 (in a leap year) or 28 otherwise.
Why it matters:Assuming the date just shifts can cause bugs or invalid dates in your application.
Quick: Does DATE_SUB always return a date earlier than the original? Commit yes or no.
Common Belief:DATE_SUB always returns a date before the original date.
Tap to reveal reality
Reality:If you subtract a negative interval, DATE_SUB can actually add time, so the result might be later.
Why it matters:Misunderstanding this can cause logic errors when dynamically calculating dates.
Quick: Can you use DATE_ADD on strings that are not valid dates? Commit yes or no.
Common Belief:You can use DATE_ADD on any string and it will work fine.
Tap to reveal reality
Reality:DATE_ADD requires a valid date or datetime value; invalid strings cause errors or NULL results.
Why it matters:Passing invalid data leads to query failures or unexpected NULLs.
Quick: Does using DATE_ADD in WHERE clauses always use indexes efficiently? Commit yes or no.
Common Belief:DATE_ADD in WHERE conditions never affects index use.
Tap to reveal reality
Reality:Using DATE_ADD on columns in WHERE can prevent index use, slowing queries.
Why it matters:Ignoring this can cause slow database performance on large tables.
Expert Zone
1
DATE_ADD and DATE_SUB handle leap seconds and daylight saving time inconsistently depending on the server timezone settings.
2
When adding months, MySQL does not count the number of days but moves the month number, which can cause unexpected results near month ends.
3
Using INTERVAL with fractional values (like 1.5 DAY) is not supported; intervals must be whole numbers, which can surprise developers expecting partial day additions.
When NOT to use
Avoid using DATE_ADD and DATE_SUB for complex calendar calculations like business days or holidays. Instead, use specialized calendar tables or application logic. For high-performance date range queries, consider storing precomputed date values or using generated columns.
Production Patterns
In production, DATE_ADD and DATE_SUB are often used for filtering recent records (e.g., last 30 days), scheduling future events, or calculating expiration dates. They are combined with indexes carefully to maintain query speed. Also, they are used in reports to show dynamic date ranges without changing stored data.
Connections
Time Zones
DATE_ADD and DATE_SUB calculations can be affected by time zone settings in MySQL.
Understanding time zones helps avoid errors when adding or subtracting time that crosses daylight saving changes or shifts server time.
Interval Arithmetic in Mathematics
DATE_ADD and DATE_SUB perform interval arithmetic similar to adding or subtracting intervals on a number line.
Knowing interval arithmetic clarifies why adding months or days is not always a simple addition but involves calendar rules.
Project Management Scheduling
DATE_ADD and DATE_SUB are used to calculate task deadlines and durations, similar to how project managers plan timelines.
Recognizing this connection helps understand the practical importance of date arithmetic in real-world planning.
Common Pitfalls
#1Adding months to dates near month end without expecting adjustment.
Wrong approach:SELECT DATE_ADD('2024-01-31', INTERVAL 1 MONTH); -- expecting '2024-02-31'
Correct approach:SELECT DATE_ADD('2024-01-31', INTERVAL 1 MONTH); -- returns '2024-02-29'
Root cause:Misunderstanding how MySQL adjusts invalid dates after adding months.
#2Using DATE_ADD on invalid date strings.
Wrong approach:SELECT DATE_ADD('not-a-date', INTERVAL 5 DAY);
Correct approach:SELECT DATE_ADD('2024-06-10', INTERVAL 5 DAY);
Root cause:Passing non-date strings causes errors or NULL results.
#3Writing WHERE clauses that prevent index use by applying DATE_ADD on columns.
Wrong approach:SELECT * FROM orders WHERE DATE_ADD(order_date, INTERVAL 7 DAY) >= CURDATE();
Correct approach:SELECT * FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);
Root cause:Applying functions on indexed columns disables index optimization.
Key Takeaways
DATE_ADD and DATE_SUB are essential MySQL functions for adding or subtracting time intervals to dates and datetimes.
They handle complex calendar rules like leap years and month lengths automatically, preventing invalid dates.
Using these functions inside queries allows dynamic date calculations without changing stored data.
Be careful with query performance: applying these functions on indexed columns can slow down searches.
Understanding how MySQL adjusts dates and handles intervals helps avoid common bugs and surprises.

Practice

(1/5)
1. What does the MySQL function DATE_ADD(date, INTERVAL expr unit) do?
easy
A. Returns the current date and time
B. Subtracts a specified time interval from a date
C. Adds a specified time interval to a date
D. Formats a date into a string

Solution

  1. Step 1: Understand the function purpose

    The function DATE_ADD is designed to add a time interval to a given date value.
  2. Step 2: Compare options with function behavior

    'Adds a specified time interval to a date' correctly states that it adds a specified time interval. 'Subtracts a specified time interval from a date' describes DATE_SUB, not DATE_ADD. The options for returning the current date and time and formatting a date into a string describe unrelated functions.
  3. Final Answer:

    Adds a specified time interval to a date -> Option C
  4. Quick Check:

    DATE_ADD adds time interval [OK]
Hint: DATE_ADD adds time; DATE_SUB subtracts time [OK]
Common Mistakes:
  • Confusing DATE_ADD with DATE_SUB
  • Thinking DATE_ADD formats dates
  • Assuming DATE_ADD returns current date
2. Which of the following is the correct syntax using DATE_SUB to subtract 10 days from the date '2024-06-15' in MySQL?
easy
A. DATE_ADD('2024-06-15', INTERVAL -10 DAY)
B. DATE_SUB('2024-06-15', INTERVAL 10 DAY)
C. DATE_SUB('2024-06-15', 10 DAY)
D. DATE_ADD('2024-06-15', 10 DAYS)

Solution

  1. Step 1: Check correct function and syntax for subtraction

    To subtract days, use DATE_SUB with INTERVAL keyword and unit DAY.
  2. Step 2: Validate each option's syntax

    DATE_SUB('2024-06-15', INTERVAL 10 DAY) uses correct syntax: DATE_SUB('date', INTERVAL 10 DAY). DATE_ADD('2024-06-15', INTERVAL -10 DAY) uses DATE_ADD with negative interval, which is not recommended. DATE_SUB('2024-06-15', 10 DAY) misses INTERVAL keyword. DATE_ADD('2024-06-15', 10 DAYS) misses the INTERVAL keyword and uses DATE_ADD which adds instead of subtracts.
  3. Final Answer:

    DATE_SUB('2024-06-15', INTERVAL 10 DAY) -> Option B
  4. Quick Check:

    Correct syntax uses DATE_SUB with INTERVAL [OK]
Hint: Use DATE_SUB with INTERVAL and unit DAY to subtract days [OK]
Common Mistakes:
  • Omitting INTERVAL keyword
  • Using plural unit like DAYS instead of DAY
  • Using DATE_ADD with negative interval
3. What is the result of this query?
SELECT DATE_ADD('2024-06-10', INTERVAL 3 MONTH) AS new_date;
medium
A. 2024-03-10
B. 2024-06-10
C. 2024-06-13
D. 2024-09-10

Solution

  1. Step 1: Understand DATE_ADD with MONTH interval

    The query adds 3 months to the date '2024-06-10'. Adding 3 months to June 10, 2024, results in September 10, 2024.
  2. Step 2: Match the calculated date with options

    2024-09-10 shows '2024-09-10', which matches the expected result. Other options are incorrect dates or no change.
  3. Final Answer:

    2024-09-10 -> Option D
  4. Quick Check:

    June 10 + 3 months = September 10 [OK]
Hint: Add months carefully; day stays same if possible [OK]
Common Mistakes:
  • Adding days instead of months
  • Confusing month addition with subtraction
  • Expecting day to change unexpectedly
4. Identify the error in this MySQL query:
SELECT DATE_SUB('2024-06-20', 5 DAY);
medium
A. Missing INTERVAL keyword before 5 DAY
B. Incorrect function name, should be DATE_ADD
C. Date format is invalid
D. DAY should be plural DAYS

Solution

  1. Step 1: Review DATE_SUB syntax

    The correct syntax requires the INTERVAL keyword before the number and unit, like DATE_SUB(date, INTERVAL expr unit).
  2. Step 2: Identify the missing keyword

    The query uses DATE_SUB('2024-06-20', 5 DAY) missing INTERVAL, causing syntax error.
  3. Final Answer:

    Missing INTERVAL keyword before 5 DAY -> Option A
  4. Quick Check:

    DATE_SUB needs INTERVAL keyword [OK]
Hint: Always include INTERVAL keyword with DATE_ADD/SUB [OK]
Common Mistakes:
  • Omitting INTERVAL keyword
  • Using plural unit DAYS instead of DAY
  • Confusing DATE_ADD and DATE_SUB
5. You want to find the date 2 weeks before the last day of the current month in MySQL using DATE_SUB. Which query correctly achieves this?
hard
A. SELECT DATE_SUB(LAST_DAY(CURDATE()), INTERVAL 2 WEEK) AS result;
B. SELECT DATE_ADD(LAST_DAY(CURDATE()), INTERVAL -2 WEEK) AS result;
C. SELECT DATE_SUB(CURDATE(), INTERVAL 2 WEEK) AS result;
D. SELECT DATE_ADD(LAST_DAY(CURDATE()), INTERVAL 2 WEEK) AS result;

Solution

  1. Step 1: Understand the requirement

    We need the date 2 weeks before the last day of the current month. LAST_DAY(CURDATE()) gives the last day of this month.
  2. Step 2: Apply correct date arithmetic

    Subtracting 2 weeks from that date is done with DATE_SUB(..., INTERVAL 2 WEEK). SELECT DATE_SUB(LAST_DAY(CURDATE()), INTERVAL 2 WEEK) AS result; uses this correctly. SELECT DATE_ADD(LAST_DAY(CURDATE()), INTERVAL -2 WEEK) AS result; uses DATE_ADD instead of DATE_SUB. SELECT DATE_SUB(CURDATE(), INTERVAL 2 WEEK) AS result; subtracts from current date, not last day. SELECT DATE_ADD(LAST_DAY(CURDATE()), INTERVAL 2 WEEK) AS result; adds 2 weeks, which is incorrect.
  3. Final Answer:

    SELECT DATE_SUB(LAST_DAY(CURDATE()), INTERVAL 2 WEEK) AS result; -> Option A
  4. Quick Check:

    Subtract 2 weeks from last day using DATE_SUB [OK]
Hint: Use LAST_DAY with DATE_SUB for relative month-end dates [OK]
Common Mistakes:
  • Subtracting from current date instead of last day
  • Using DATE_ADD with positive interval instead of subtraction
  • Confusing weeks with days in interval
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard