SQL DATEDIFF Function

The SQL DATEDIFF function is used to calculate the difference between two dates in terms of days. It returns the number of days between the start date and the end date. This function is commonly used in reporting, tracking events, and calculating age.

In this tutorial, we will explore the DATEDIFF function, its syntax, and practical examples.


Syntax of SQL DATEDIFF Function

The syntax of the DATEDIFF function varies slightly depending on the database system, but the general format is:

</>
Copy
SELECT DATEDIFF(end_date, start_date);

Parameters:

  • start_date: The starting date (earlier date).
  • end_date: The ending date (later date).
  • Returns: The number of days between start_date and end_date.

The function counts the number of whole days between the two dates and does not consider time differences.


Step-by-Step Examples Using SQL DATEDIFF

1 Calculating the Difference Between Two Dates

Let’s say we need to calculate the number of days between ‘2024-02-01’ and ‘2024-02-12’. We can use the following query:

</>
Copy
SELECT DATEDIFF('2024-02-12', '2024-02-01') AS days_difference;

Output: