SQL Functions   «Prev  Next»
Lesson 14The DATEDIFF function
ObjectiveLearn how to use the DATEDIFF function.

Explain How to Use the SQL DATEDIFF() Function

The DATEDIFF() function is used when you want to measure the distance between two dates or datetime values. Instead of generating a new future or past date, as DATEADD() does, DATEDIFF() tells you how much time lies between two temporal values. This makes it useful for report queries, aging analysis, employment-duration calculations, service intervals, publication timelines, and many other kinds of business reporting. :contentReference[oaicite:0]{index=0}

In practical SQL work, many questions are really questions about elapsed time. How many days has an invoice been open? How many months passed between two releases? How long was an employee employed? How old is a transaction? These are exactly the kinds of questions that DATEDIFF() is designed to answer. Once you understand the function’s arguments, interval units, and integer-return behavior, it becomes one of the most useful tools in temporal SQL. :contentReference[oaicite:1]{index=1}

What DATEDIFF() Does

The purpose of DATEDIFF() is to compare two temporal values and return the difference in a chosen unit. The function measures the interval between a starting date and an ending date, using a date part such as day, week, month, or year. This makes it different from functions that merely display or extract date information. DATEDIFF() is a measurement function. It answers the question: how far apart are these two values?

A general form of the syntax is:

DATEDIFF(unit, date1, date2)

Here, unit identifies the kind of interval to measure, while date1 and date2 are the two values being compared. The function then returns an integer representing the difference in that chosen unit. :contentReference[oaicite:2]{index=2}

Understanding the Three Arguments

The function becomes much easier to use once its three arguments are understood clearly:

  1. unit specifies the date part to measure, such as day, week, month, or year.
  2. date1 is the starting reference point.
  3. date2 is the ending reference point.

Those three parts define the meaning of the result. If the interval is day, the function returns a day-based difference. If the interval is month, it returns a month-based difference. The same two dates can therefore produce very different answers depending on which unit is chosen. That is why interval selection matters just as much as the dates themselves. :contentReference[oaicite:3]{index=3}

Common Interval Units

The lesson materials include a broad list of datepart options that may be available depending on the SQL dialect. Common examples include:

  • year
  • quarter
  • month
  • dayofyear
  • day
  • week
  • weekday
  • hour
  • minute
  • second
  • millisecond
  • microsecond
  • nanosecond

Not every database system supports exactly the same interval names or abbreviations, and some engines define certain units differently from others. That is why vendor documentation still matters. The conceptual use of DATEDIFF() is portable, but the exact supported date parts may vary by platform. :contentReference[oaicite:4]{index=4}

Why the Order of the Dates Matters

One of the most important practical points about DATEDIFF() is that the order of the dates matters. If the second date occurs after the first date, the result is usually positive. If the second date occurs before the first date, the result may be negative. Reversing the arguments therefore changes the meaning of the result.

This matters because the function is often used in business logic where the sign of the value carries meaning. A positive number may indicate time elapsed since an event began, while a negative number may signal that the event actually lies in the future relative to the chosen starting point. If the arguments are reversed carelessly, the query may still run but the meaning of the answer changes. :contentReference[oaicite:5]{index=5}

DATEDIFF() Returns an Integer

The lesson materials also emphasize that DATEDIFF() returns an integer difference without rounding. This is an important point because some learners expect a fractional result. Instead, the function returns a whole-number count in the specified unit. The result therefore depends on how the DBMS counts the interval boundaries defined by the date part.

That means the same two dates may produce results such as:

  • 44 days,
  • 7 weeks,
  • 1 month,
  • 0 years.

The function is not inconsistent in those cases. It is simply answering different questions based on the chosen unit. This is why the interval argument shapes interpretation so strongly. :contentReference[oaicite:6]{index=6}

A Practical Employment-Duration Example

A strong example from the source material measures the duration of employment in days:

SELECT
  employee_id,
  DATEDIFF(DAY, hire_date, termination_date) AS employment_duration
FROM employees;

This query returns each employee identifier along with the number of days between the hire date and termination date. It is a clear business use case because it shows how DATEDIFF() supports human-resources analysis, tenure reporting, and elapsed-time measurement in real systems. It also reinforces the importance of argument order: the query reads naturally from hire date to termination date, so the result reflects forward elapsed time. :contentReference[oaicite:7]{index=7}

A Simple Week-Difference Example

The lesson also includes a literal-date example that measures the difference in weeks between May 2, 1998 and June 15, 1998:

SELECT DATEDIFF(week, '5/2/1998', '6/15/1998')

The result is 7 weeks. This example is useful because it shows how the same two dates can be interpreted at different levels. Once the learner sees the week difference, it becomes natural to ask related questions: what is the difference in days, months, or years? The answer changes depending on the date part being used, and that reinforces the central lesson that DATEDIFF() measures elapsed time according to the unit you choose. :contentReference[oaicite:8]{index=8}

DATEDIFF() in SQL Server

The lesson materials place special emphasis on Microsoft SQL Server, where DATEDIFF() is commonly written in the form:

DATEDIFF(datepart, startdate, enddate)

This version highlights the same three core ideas already discussed: the date part, the starting value, and the ending value. In SQL Server documentation and examples, common datepart values often include year, quarter, month, dayofyear, day, hour, minute, and second. A practical example from the lesson calculates the number of days between two fixed dates:

SELECT DATEDIFF(day, '2024-01-01', '2024-08-21') AS DifferenceInDays;

This returns an integer result of 233. Another example measures the number of months between two dates:

SELECT DATEDIFF(month, '2023-01-15', '2024-08-15') AS DifferenceInMonths;

That returns 19. These examples are useful because they show how the same function can answer different business questions simply by changing the chosen date part. :contentReference[oaicite:9]{index=9}

Using Subqueries with DATEDIFF()

The lesson also includes examples that show DATEDIFF() working with values returned by subqueries. This is important because real SQL often needs to compare dates drawn from different rows or aggregated sources, not just fixed literals.

One example counts the days between two publication dates:

SELECT datediff("d", date1, date2) AS days
FROM
    (SELECT pubdate AS date1
     FROM titles
     WHERE title_id = 'T05') t1,
    (SELECT pubdate AS date2
     FROM titles
     WHERE title_id = 'T06') t2;

Another example counts the months between the earliest and latest publication dates in a table:

SELECT datediff("m", date1, date2) AS months
FROM
    (SELECT
        MIN(pubdate) AS date1,
        MAX(pubdate) AS date2
     FROM titles) t1;

These examples are especially valuable because they show that DATEDIFF() is not limited to one-row comparisons. It can also be used in more advanced analytical patterns involving aggregation and subqueries. :contentReference[oaicite:10]{index=10}

DATEDIFF() Versus DATEADD()

Because this lesson follows earlier work on DATEADD(), it helps to draw the distinction clearly. The two functions are related, but they do different jobs:

  • DATEADD() answers: What date do I get after adding an interval?
  • DATEDIFF() answers: How much time lies between these two dates?

That distinction matters in reporting logic. A billing query might use DATEADD() to calculate a due date, while an aging report might use DATEDIFF() to calculate how long an invoice has remained unpaid. One function creates a shifted date. The other measures elapsed distance. They complement one another, but they are not interchangeable. :contentReference[oaicite:11]{index=11}

Why DATEDIFF() Matters in Reporting

The reason DATEDIFF() appears so often in SQL is that elapsed time is one of the most important dimensions in business reporting. Organizations routinely need to know how long something has been open, how much time passed between two events, or how old a record is relative to the current date. These are not edge cases. They are mainstream reporting requirements.

That makes DATEDIFF() useful in:

  • aging reports,
  • employee tenure calculations,
  • service-level monitoring,
  • subscription and renewal analysis,
  • publication and release timelines,
  • historical comparison queries.

In all of these cases, the function turns stored temporal values into a measurable interval that can be interpreted, sorted, grouped, and reported. :contentReference[oaicite:12]{index=12}

Conclusion

The DATEDIFF() function is one of the most practical SQL tools for elapsed-time analysis. It compares two dates or datetimes and returns an integer difference in a chosen unit such as days, weeks, months, or years. To use it correctly, the developer must understand three things clearly: the interval unit, the order of the arguments, and the fact that the result is an integer rather than a fractional duration.

Once those points are understood, DATEDIFF() becomes a powerful reporting function. It helps measure employment duration, compare publication dates, analyze aging windows, and support many other forms of time-based business logic. That is why it remains a foundational part of practical SQL date arithmetic. :contentReference[oaicite:13]{index=13}


SEMrush Software 14 SEMrush Banner 14