SQL Resources
SQL
DATE_DIFF

DATE_DIFF

DATE_DIFF

See also DATETIME_DIFF, TIMESTAMP_DIFF, TIME_DIFF

Definition

The DATE_DIFF function allows you to find the difference between 2 date objects in the specified date_part interval.

Syntax

DATE_DIFF(date_expression_a, date_expression_b, date_part)

Where date_part can be any of the following:

  • DAY
  • WEEK : Begins on Sunday
  • WEEK(): Begins on  where WEEKDAY can be SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.
  • ISOWEEK: Uses ISO 8601 week boundaries. ISO weeks begin on Monday.
  • MONTH
  • QUARTER
  • YEAR
  • ISOYEAR: Uses the ISO 8601 week-numbering year boundary. The ISO year boundary is the Monday of the first week whose Thursday belongs to the corresponding Gregorian calendar year.
  • SELECT
      DATE_DIFF(CAST('2021-01-01' AS DATE), CAST('2020-01-01' AS DATE), DAY) AS days_difference,
      DATE_DIFF(CAST('2021-01-01' AS DATE), CAST('2021-02-01' AS DATE), WEEK) AS weeks_difference
    days_differenceweeks_difference
    366-5

    Practical Info

  • If the first date is earlier than the second one then the output will be negative.
  • Common Questions

    How to filter for the last n days?

    A common SQL query WHERE clause is to just pull the data for the last n days. In this case, we can make use of DATE_DIFF and CURRENT_DATE:

    SELECT
      date,
      DATE_DIFF(CURRENT_DATE(), date, DAY) AS days_since
    FROM
      (
        SELECT
          CAST('2021-01-22' AS DATE) AS date
        UNION ALL
    (    SELECT
          CAST('2020-01-25' AS DATE) AS date)
        UNION ALL
    (    SELECT
          CAST('2021-01-26' AS DATE) AS date)
      ) AS table_3
    WHERE
      (DATE_DIFF(CURRENT_DATE(), date, DAY) <= 30)
    datedays_since
    2021-01-2221
    2021-01-2617

    Troubleshooting Common Errors

    Argument 2 of DATE_DIFF has incorrect type: expected date found datetime.

    This one is all too common. If you're using DATE_DIFF, you'll need to make sure both of your dates are indeed DATE data types, and not DATETIME or TIMESTAMPs. It's usually easy enough to add a CAST(datetime_col as DATE) to your function:

    DATE_DIFF(CAST('2020-01-01 10:44:22' as DATE),'2021-01-05', DAY) days_diff

    DATE_DIFF does not support the SECOND date part

    Similar to the first common error, this about the compatibility of the argument data types and the function. To find the difference between times, you'll need to use DATETIME_DIFF, TIMESTAMP_DIFF, or TIME_DIFF.

    Related Pages

  • DATETIME_DIFF
  • TIMESTAMP_DIFF
  • Dates & Times in BigQuery
  • Subscribe to newsletter

    Subscribe to receive the latest blog posts to your inbox every week.

    By subscribing you agree to our Privacy Policy.
    Thank you! Your submission has been received!
    Oops! Something went wrong while submitting the form.

    Start solving your organization's biggest problems with Count today.

    Stay up to date with all things count, data and problem solving.