π» Introduction
Dates and times are crucial in SQL for tracking events, filtering records, and reporting. Functions like CURRENT_DATE, DATEADD, DATEDIFF, and EXTRACT make handling date operations much easier.
1οΈβ£ CURRENT_DATE β Todayβs Date
The CURRENT_DATE function returns the current system date.
SELECT CURRENT_DATE AS Today;
-- Output β 2025-09-28
2οΈβ£ DATEADD β Adding to Dates
The DATEADD function adds a specified time interval (days, months, years) to a date.
SELECT DATEADD(DAY, 7, '2025-09-28') AS NextWeek;
-- Output β 2025-10-05
3οΈβ£ DATEDIFF β Difference Between Dates
The DATEDIFF function calculates the difference between two dates (in days, months, or years).
SELECT DATEDIFF(DAY, '2025-01-01', '2025-09-28') AS DaysBetween;
-- Output β 270
4οΈβ£ EXTRACT β Getting Parts of a Date
The EXTRACT function pulls out specific parts of a date (year, month, day, etc.).
SELECT EXTRACT(YEAR FROM '2025-09-28') AS YearPart,
EXTRACT(MONTH FROM '2025-09-28') AS MonthPart,
EXTRACT(DAY FROM '2025-09-28') AS DayPart;
-- Output β 2025 | 9 | 28
Tip: Use date functions in WHERE clauses to filter by time periods, e.g.,
WHERE OrderDate >= DATEADD(DAY, -30, CURRENT_DATE).β Key Takeaways
CURRENT_DATEβ Get todayβs dateDATEADDβ Add time intervalsDATEDIFFβ Find difference between datesEXTRACTβ Extract year, month, day- Helps in filtering, reporting, and analytics
π Quick Reference β Common SQL Date Functions
| Function | Description | Example | Result |
|---|---|---|---|
| CURRENT_DATE | Returns todayβs date | CURRENT_DATE |
2025-09-28 |
| DATEADD(interval, n, date) | Adds n units of interval to a date | DATEADD(DAY, 10, '2025-09-28') |
2025-10-08 |
| DATEDIFF(interval, d1, d2) | Difference between two dates | DATEDIFF(DAY, '2025-01-01','2025-09-28') |
270 |
| EXTRACT(field FROM date) | Extracts year, month, day | EXTRACT(MONTH FROM '2025-09-28') |
9 |
π Continue Learning
π¬ Got a question about SQL Date Functions? Drop it in the comments below and letβs discuss!