SQL Date Functions




πŸ’» 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 date
  • DATEADD β†’ Add time intervals
  • DATEDIFF β†’ Find difference between dates
  • EXTRACT β†’ 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!




Leave a Comment