SQL Server функция DATEDIFF
В SQL Server (Transact-SQL) функция DATEDIFF возвращает разность между двумя значениями даты в зависимости от указанного интервала.
Синтаксис
Синтаксис функции DATEDIFF в SQL Server (Transact-SQL):
Параметры или аргументы
interval — интервал времени для вычисления разницы между date1 и date2 . Это может быть одно из следующих значений:
| Значение (любое из) | Пояснение |
|---|---|
| year, yyyy, yy | Год интервал |
| quarter, qq, q | Квартал интервал |
| month, mm, m | Месяца интервал |
| dayofyear | День года интервал |
| day, dy, y | День интервал |
| week, ww, wk | Неделя интервал |
| weekday, dw, w | День недели интервал |
| hour, hh | Час интервал |
| minute, mi, n | Минуты интервал |
| second, ss, s | Секунды интервал |
| millisecond, ms | Миллисекунды интервал |
| microsecond, mcs | Микросекунды интервал |
| nanosecond, ns | Наносекунды интервал |
date1 , date2 — две даты для расчета разницы между ними.
Применение
Функция DATEDIFF может использоваться в следующих версиях SQL Server (Transact-SQL):
SQL Server vNext, SQL Server 2016, SQL Server 2015, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005
Пример
Рассмотрим некоторые примеры SQL Server функции DATEDIFF, чтобы понять, как использовать функцию DATEDIFF в SQL Server (Transact-SQL). Например:
Что делают в SQL текущая дата и другие функции даты и времени страница 2
Функции, возвращающие текущие дату, время, дату и время
CURDATE(), CURRENT_DATE(), CURRENT_DATE — возвращают текущую дату в формате ‘YYYY-MM-DD’ или YYYYDDMM в зависимости от того, вызывается функция в текстовом или числовом контексте.
CURTIME(), CURRENT_TIME(), CURRENT_TIME — возвращают текущее время суток в формате ‘hh-mm-ss’ или hhmmss в зависимости от того, вызывается функция в текстовом или числовом контексте.
NOW() — возвращает текущие дату и время формате ‘YYYY-MM-DD hh:mm:ss’ или YYYYDDMMhhmmss в зависимости от того, вызывается функция в текстовом или числовом контексте.
Функции для вычисления разницы между моментами
TIMEDIFF(param1, param2) — возвращает разницу между значениями времени, заданными параметрами param1 и param2.
DATEDIFF(param1, param2) — возвращает разницу между датами param1 и param2. Значения param1 и param2 могут иметь типы DATE или DATETIME, а при вычислении разницы используется лишь часть DATE.
PERIOD_DIFF(param1, param2) — возвращает разницу в месяцах между датами param1 и param2. Значения param1 и param2 могут быть представлены в числовом формате YYYYMM или YYMM.
TIMESTAMPDIFF(interval, param1, param2) — возвращает разницу между значениями датами param1 и param2. Значения param1 и param2 могут быть представлены в форматах ‘YYYY-MM-DD’ или ‘YYYY-MM-DD hh:mm:ss’. Единица измерения разницы задаётся параметром interval. Он может принимать значения FRAC_SECOND (микросекунды), SECOND (секунды), MINUTE (минуты), HOUR (часы), DAY (дни), WEEK (недели), MONTH (месяцы), QUARTER (кварталы), YEAR (годы).
Как посчитать разницу в sql

The DIFFERENCE() function compares two different SOUNDEX values, and return the value of the integer. This value measures the degree that the SOUNDEX values match, on a scale of 0 to 4. A value of 0 indicates a weak or no similarity between the SOUNDEX values; 4 indicates that the SOUNDEX values are extremely similar, or even identical.
Syntax :
Parameter : This method accepts two-parameters as mentioned above and described below –
- string, string –
It is an alphanumeric expression of character data. It can be a constant, variable, or column.
Returns : It returns an integer value measuring the difference between the SOUNDEX() values of two different string.
Example-1 :
Using DIFFERENCE() function with similar SOUNDEX() values.
Output :
| soundex_poor | soundex_pour | similarity |
|---|---|---|
| P600 | P600 | 4 |
Example-2 :
Returns a DIFFERENCE value of 3, the less possible difference.
Output :
Example-3 :
Returns a DIFFERENCE value of 2, the medium possible difference.
Output :
| soundex_GeeksForGeeks | soundex_GFG | similarity |
|---|---|---|
| G216 | G120 | 2 |
Example-4 :
Returns a DIFFERENCE value of 0, the highest possible difference.
SQL DATEDIFF
Summary: in this tutorial, you will learn how to use the SQL DATEDIFF() function to calculate the difference between two dates.
Syntax
To calculate the difference between two dates, you use the DATEDIFF() function. The following illustrates the syntax of the DATEDIFF() function in SQL Server:
Arguments
datepart
The datepart is a part of the date in which you want the function to return. The following table illustrates the valid parts of date in SQL Server:
| Valid Date Part | Abbreviations |
|---|---|
| year | yy, yyyy |
| quarter | qq, q |
| month | mm, m |
| dayofyear | dy, y |
| day | dd, d |
| week | wk, ww |
| weekday | dw, w |
| hour | hh |
| minute | mi, n |
| second | ss, s |
| millisecond | ms |
| microsecond | mcs |
| nanosecond | ns |
startdate, enddate
The startdate and enddate are date literals or expressions from which you want to find the difference.
Return
The DATEDIFF() function returns an integer value with the unit specified by the datepart argument.
Examples
The following example returns the number of year between two dates:
Here is the result:
To get the number of month or day, you change the first argument to month or day as shown below:
The following shows the result:
Notice that the DATEDIFF() function takes the leap year into account. As shown clearly in the result, because 2016 is the leap year, the difference in days between two dates is 2×365 + 366 = 1096.
The following example illustrates how to use the DATEDIFF() function to calculate the difference in hours between two DATETIME values:
Consider the following example:
It also returns two because the DATEDIFF() function returns an integer only. In this case, it truncated the minute part and only consider the hour part.
The following example shows how to use the DATEDIFF() function to calculate the year of services of employees up to January 1st, 2018:
DATEDIFF in MySQL
Unlike SQL Server, MySQL has a slightly different DATEDIFF() function syntax:
MySQL only returns the difference between two dates in days. It ignores all the time part of the date in the calculation. See the following example:
The result is nine days:
In this tutorial, you have learned how to use the SQL DATEDIFF() function to calculate the difference between two dates.