|
1 | 1 | ---
|
2 |
| -title: DATE DIFF |
| 2 | +title: DATE_DIFF |
3 | 3 | ---
|
| 4 | +import FunctionDescription from '@site/src/components/FunctionDescription'; |
4 | 5 |
|
5 |
| -Databend does not provide a `date_diff` function yet, but it supports direct arithmetic operations on dates and times. For example, you can use the expression `TO_DATE(NOW())-2` to obtain the date from two days ago. |
| 6 | +<FunctionDescription description="Introduced or updated: v1.2.645"/> |
6 | 7 |
|
7 |
| -This flexibility of directly manipulating dates and times in Databend makes it convenient and versatile for handling date and time computations. See an example below: |
| 8 | +Calculates the difference between two dates or timestamps based on a specified time unit. The result is positive if the `<end_date>` is after the `<start_date>`, and negative if it's before. |
| 9 | + |
| 10 | +## Syntax |
| 11 | + |
| 12 | +```sql |
| 13 | +DATE_DIFF(<unit>, <start_date>, <end_date>) |
| 14 | +``` |
| 15 | + |
| 16 | +| Parameter | Description | |
| 17 | +|----------------|-------------------------------------------------------------------------------------------------------------| |
| 18 | +| `<unit>` | The time unit for the difference: `YEAR`, `QUARTER`, `MONTH`, `WEEK`, `DAY`, `HOUR`, `MINUTE`, or `SECOND`. | |
| 19 | +| `<start_date>` | The starting date or timestamp. | |
| 20 | +| `<end_date>` | The ending date or timestamp. | |
| 21 | + |
| 22 | +## Examples |
| 23 | + |
| 24 | +This example calculates the difference in hours between **yesterday** and **today**: |
8 | 25 |
|
9 | 26 | ```sql
|
10 |
| -CREATE TABLE tasks ( |
11 |
| - task_name VARCHAR(50), |
12 |
| - start_date DATE, |
13 |
| - end_date DATE |
14 |
| -); |
15 |
| - |
16 |
| -INSERT INTO tasks (task_name, start_date, end_date) |
17 |
| -VALUES |
18 |
| - ('Task 1', '2023-06-15', '2023-06-20'), |
19 |
| - ('Task 2', '2023-06-18', '2023-06-25'), |
20 |
| - ('Task 3', '2023-06-20', '2023-06-23'); |
21 |
| - |
22 |
| -SELECT task_name, end_date - start_date AS duration |
23 |
| -FROM tasks; |
24 |
| - |
25 |
| -┌────────────────────────────────────┐ |
26 |
| -│ task_name │ duration │ |
27 |
| -├──────────────────┼─────────────────┤ |
28 |
| -│ Task 1 │ 5 │ |
29 |
| -│ Task 2 │ 7 │ |
30 |
| -│ Task 3 │ 3 │ |
31 |
| -└────────────────────────────────────┘ |
| 27 | +SELECT DATE_DIFF(HOUR, YESTERDAY(), TODAY()); |
| 28 | + |
| 29 | +-[ RECORD 1 ]----------------------------------- |
| 30 | +DATE_DIFF(HOUR, yesterday(), today()): 24 |
32 | 31 | ```
|
| 32 | + |
| 33 | +This example calculates the difference in years between the current date and January 1, 2000; |
| 34 | + |
| 35 | +```sql |
| 36 | +SELECT NOW(), DATE_DIFF(YEAR, NOW(), TO_DATE('2000-01-01')); |
| 37 | + |
| 38 | +-[ RECORD 1 ]----------------------------------- |
| 39 | + now(): 2024-10-15 03:06:37.202434 |
| 40 | +DATE_DIFF(YEAR, now(), to_date('2000-01-01')): -24 |
| 41 | +``` |
0 commit comments