SQL Query to Calculate Total Number of Days Between Two Specific Dates
Last Updated :
16 Dec, 2024
Calculating the difference between dates is a common requirement in SQL, especially for tasks related to time tracking, project management, and historical data analysis. SQL provides various tools to work with date and time data, and one of the most straightforward is the DATEDIFF() function. This function allows us to efficiently compute the difference in days, or other units, between two dates.
In this article, we’ll explain how to calculate the total number of days between two specific dates using SQL, with the help of the DATEDIFF() function. We’ll also provide examples to demonstrate its usage step by step.
1. Using DATEDIFF() Function
The most straightforward method to calculate the difference in days between two dates in SQL is by using the DATEDIFF() function. This function returns the difference in days between the start date and the end date.
Syntax
DATEDIFF(day or dy or y, <start_date>, <end_date>);
Key Terms
- day: Specifies that the difference should be calculated in days.
- start_date: The starting date.
- end_date: The ending date.
Calculating Total Number of Days Between Two Specific Dates
Here, we will learn how to calculate the total number of days between two specific dates in SQL. To demonstrate the use of DATEDIFF(), let’s calculate the number of days between the purchase dates of two items from a sample orders table.
Step 1: Create a Demo Database and Table
First, we’ll create a database called geeks
and a table named demo_orders
, which contains details about various orders. Use the below SQL statement to create a database called geeks.
Query:
CREATE DATABASE geeks;
USE geeks;
CREATE TABLE demo_orders(
ORDER_ID INT IDENTITY(1,1) PRIMARY KEY,
ITEM_NAME VARCHAR(30) NOT NULL,
ORDER_DATE DATE
);
INSERT INTO demo_orders
VALUES
('Maserati', '2007-10-03'),
('BMW', '2010-07-23'),
('Mercedes Benz', '2012-11-12'),
('Ferrari', '2016-05-09'),
('Lamborghini', '2020-10-20');
SELECT * FROM demo_orders;
Output

Step 2: Using DATEDIFF() to Calculate the Difference
Now let's find the number of days between the dates of the order of 'Maserati' and 'Ferrari' in the table using DATEDIFF() function. This result indicates that 3,136 days passed between the purchase dates of 'Maserati' and 'Ferrari'.
Query:
DECLARE
@start VARCHAR(10) = (
SELECT order_date FROM demo_orders
WHERE item_name = 'Maserati'),
@end VARCHAR(10) = (
SELECT order_date FROM demo_orders
WHERE item_name = 'Ferrari')
--@start variable holds the start date(i.e date of Maserati being purchased).
--@end variable holds the end date (i.e date of Ferrari being purchased).
SELECT DATEDIFF(day, @start, @end) AS number_of_days;
Output
Explanation:
The @start variable stores the purchase date of 'Maserati' (2007-10-03
), while the @end variable holds the purchase date of 'Ferrari' (2016-05-09
). By using these two variables as inputs, the DATEDIFF() function calculates the difference in days between the two dates, providing a precise measure of the time interval. This approach simplifies date calculations by dynamically referencing specific dates from the database, ensuring accuracy and flexibility.
Comparing DATEDIFF with Other Methods
The DATEDIFF() function is not the only way to calculate date differences in SQL. However, it is often the most convenient and efficient.
Key Advantages:
- Simplicity: Easy to use with minimal syntax.
- Flexibility: Supports various date parts like days, months, and years.
- Accuracy: Handles leap years and varying month lengths automatically.
Example Use Cases:
- Calculating the age of a customer based on their date of birth.
- Measuring the duration of a project or event.
- Analyzing trends over specific time intervals.
Conclusion
Calculating the total number of days between two specific dates in SQL is a straightforward operation with the DATEDIFF() function. By using this function, we can perform date calculations efficiently, whether for tracking time intervals, analyzing historical data, or generating reports. Understanding how to use DATEDIFF() and its parameters enables us to handle various date-related queries with confidence. Practice these techniques, and we’ll find date calculations in SQL become second nature.
Similar Reads
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
ACID Properties in DBMS
In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read