Tracking time is central to modern software applications: user registration dates, order timestamps, subscription renewal periods, and loan interest schedules. SQL includes robust Date and Time Functions for manipulating calendar intervals and time zones.
| Function & Syntax | Operation Performed | Example & Output |
|---|---|---|
| NOW() / CURRENT_TIMESTAMP | Returns current system date and time. | '2026-11-06 20:54:49' |
| CURDATE() / CURRENT_DATE | Returns current calendar date only. | '2026-11-06' |
| DATE_ADD(date, INTERVAL expr unit) | Adds an interval (days, months, years) to a date. | DATE_ADD('2026-01-01', INTERVAL 30 DAY) |
| DATEDIFF(date1, date2) | Returns integer days between date1 - date2. |
DATEDIFF('2026-11-06', '2026-11-01') → 5 |
| EXTRACT(unit FROM date) | Extracts YEAR, MONTH, DAY, HOUR. | EXTRACT(YEAR FROM NOW()) → 2026 |
| DATE_FORMAT(date, format) | Formats date into custom string layout. | DATE_FORMAT(NOW(), '%W, %M %Y') |
-- Calculate total enrolled days and extract graduation year
SELECT
student_id,
first_name,
enrollment_date,
DATEDIFF(CURRENT_DATE, enrollment_date) AS days_enrolled,
DATE_ADD(enrollment_date, INTERVAL 3 YEAR) AS expected_graduation_date
FROM students;
Next, let us learn conditional logic using the SQL CASE Expression!
CURDATE() returns only the current calendar date ('YYYY-MM-DD'). NOW() returns both current date and current time ('YYYY-MM-DD HH:MM:SS').
In MySQL, use DATEDIFF(date1, date2). In PostgreSQL, simply subtract two dates: date1 - date2.
EXTRACT(field FROM source) extracts individual sub-components (such as YEAR, MONTH, DAY, HOUR) from a date or timestamp.
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 29: CASE Expression → Previous: ← Math Functions | Full Syllabus
Differences between DATE, TIME, DATETIME, and TIMESTAMP.
Filtering historical records with BETWEEN and intervals.
Partitioning high-volume tables by year and month.
Aggregating revenue and counts by year, quarter, and month.