SQL Server Queries - Get days between two dates
SQL Server Queries - Get days between two dates
Getting the Number of Days Between Two Dates in SQL Server
In SQL Server, you can calculate the number of days between two dates using the `DATEDIFF` function. Here's how to do it.
Syntax
The syntax to get the number of days between two dates is as follows:
SELECT DATEDIFF(day, @startDate, @endDate) AS DaysBetween; This query returns the number of days between the `@startDate` and `@endDate` variables.
Example
Let's say we want to calculate the number of days between '2023-03-01' and '2023-03-15':
DECLARE @startDate DATE = '2023-03-01'; DECLARE @endDate DATE = '2023-03-15'; SELECT DATEDIFF(day, @startDate, @endDate) AS DaysBetween; This query will return the result:
| DaysBetween |
|---|
| 14 |
The result shows that there are 14 days between '2023-03-01' and '2023-03-15'.
Using a Table Column
If you want to calculate the number of days between two dates in a table column, you can use the following syntax:
SELECT DATEDIFF(day, StartDate, EndDate) AS DaysBetween FROM YourTableName; This query will return the number of days between the `StartDate` and `EndDate` columns for each row in the table.
Example Output
The output of the query will be a list of the number of days between the start and end dates for each row. Here's an example output:
| DaysBetween |
|---|
| 14 |
| 7 |
| 21 |
In this example, the output includes the number of days between the start and end dates for each row in the table.
In this example, the output includes the number of days between the start and end dates for each row in the table.
-->