🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Date and Time Functions

SQL FunctionsDate/TimeđŸŸĸ Free Lesson
SQL Functions

Date and Time Functions

Master SQL date and time functions to extract parts, format dates, calculate intervals, and perform temporal analysis.

  • Extract & Transform — Pull year, month, day, and hour from any datetime column
  • Calculate Intervals — Add or subtract days, months, and years from dates Time-series analysis starts with mastering date functions.

Getting the Current Date and Time

Date/Time Function TimelineNOW()Current timestampEXTRACTYEAR / MONTH / DAYDATE_TRUNCRound to precisionINTERVALAdd / Subtract timeDATEDIFFDays between datesTO_CHARFormat outputCommon Usage PatternSELECT EXTRACT(YEAR FROM order_date), DATE_TRUNC('month', order_date) + INTERVAL '7' DAY
-- Get current date and timestamp
SELECT
    CURRENT_DATE AS today,
    NOW() AS current_timestamp,
    CURRENT_TIMESTAMP AS also_now;
-- PostgreSQL-specific: extract with timezone
SELECT
    NOW() AS utc_now,
    NOW() AT TIME ZONE 'America/New_York' AS ny_time,
    NOW() AT TIME ZONE 'Asia/Tokyo' AS tokyo_time;

Extracting Parts from Dates

-- Extract year, month, and day from order dates
SELECT
    order_id,
    order_date,
    EXTRACT(YEAR FROM order_date) AS order_year,
    EXTRACT(MONTH FROM order_date) AS order_month,
    EXTRACT(DAY FROM order_date) AS order_day,
    EXTRACT(DOW FROM order_date) AS day_of_week
FROM orders;
-- MySQL alternative using DATE_FORMAT
SELECT
    order_id,
    YEAR(order_date) AS order_year,
    MONTH(order_date) AS order_month,
    DAY(order_date) AS order_day,
    DAYOFWEEK(order_date) AS day_of_week
FROM orders;

Common Date Parts Reference

PartPostgreSQLMySQLSQL Server
YearEXTRACT(YEAR FROM date)YEAR(date)YEAR(date)
MonthEXTRACT(MONTH FROM date)MONTH(date)MONTH(date)
DayEXTRACT(DAY FROM date)DAY(date)DAY(date)
Day of WeekEXTRACT(DOW FROM date)DAYOFWEEK(date)DATEPART(WEEKDAY, date)
Day of YearEXTRACT(DOY FROM date)DAYOFYEAR(date)DATEPART(DAYOFYEAR, date)

Formatting Dates

-- PostgreSQL: format dates as readable strings
SELECT
    order_id,
    order_date,
    TO_CHAR(order_date, 'Month DD, YYYY') AS long_date,
    TO_CHAR(order_date, 'MM/DD/YYYY') AS us_format,
    TO_CHAR(order_date, 'DD-MM-YYYY HH24:MI') AS full_datetime
FROM orders;
-- MySQL: format dates using DATE_FORMAT
SELECT
    order_id,
    DATE_FORMAT(order_date, '%M %d, %Y') AS long_date,
    DATE_FORMAT(order_date, '%m/%d/%Y') AS us_format,
    DATE_FORMAT(order_date, '%d-%m-%Y %H:%i') AS full_datetime
FROM orders;

Format Patterns Cheat Sheet

PatternPostgreSQLMySQLExample Output
Full MonthMonth%MJanuary
Abbreviated MonthMon%bJan
Zero-padded DayDD%d05
4-digit YearYYYY%Y2026
24-hour TimeHH24:MI%H:%i14:30

Date Arithmetic

-- Add and subtract intervals from dates
SELECT
    CURRENT_DATE AS today,
    CURRENT_DATE + INTERVAL '7' DAY AS next_week,
    CURRENT_DATE - INTERVAL '30' DAY AS last_month,
    CURRENT_DATE + INTERVAL '3' MONTH AS three_months,
    CURRENT_DATE + INTERVAL '1' YEAR AS next_year;
-- MySQL equivalent using DATE_ADD and DATE_SUB
SELECT
    CURDATE() AS today,
    DATE_ADD(CURDATE(), INTERVAL 7 DAY) AS next_week,
    DATE_SUB(CURDATE(), INTERVAL 30 DAY) AS last_month,
    DATE_ADD(CURDATE(), INTERVAL 3 MONTH) AS three_months;
-- Calculate days between two dates
SELECT
    order_id,
    order_date,
    CURRENT_DATE - order_date AS days_since_order,
    EXTRACT(DAY FROM AGE(CURRENT_DATE, order_date)) AS days_old
FROM orders;

Date Difference Functions

-- PostgreSQL: use AGE() for human-readable differences
SELECT
    employee_name,
    hire_date,
    AGE(CURRENT_DATE, hire_date) AS tenure,
    EXTRACT(YEAR FROM AGE(CURRENT_DATE, hire_date)) AS years_employed
FROM employees;
-- MySQL: use DATEDIFF for day counts
SELECT
    employee_name,
    hire_date,
    DATEDIFF(CURDATE(), hire_date) AS days_employed,
    DATEDIFF(CURDATE(), hire_date) / 365 AS approx_years
FROM employees;

Truncating Dates

-- Group orders by month using DATE_TRUNC
SELECT
    DATE_TRUNC('month', order_date) AS month,
    COUNT(*) AS total_orders,
    SUM(amount) AS monthly_revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
-- Group by quarter
SELECT
    DATE_TRUNC('quarter', order_date) AS quarter,
    COUNT(*) AS order_count,
    AVG(amount) AS avg_order_value
FROM orders
GROUP BY DATE_TRUNC('quarter', order_date)
ORDER BY quarter;

Conditional Date Logic

-- Classify orders by recency
SELECT
    order_id,
    order_date,
    CASE
        WHEN order_date >= CURRENT_DATE - INTERVAL '7' DAY THEN 'This Week'
        WHEN order_date >= CURRENT_DATE - INTERVAL '30' DAY THEN 'This Month'
        WHEN order_date >= CURRENT_DATE - INTERVAL '90' DAY THEN 'This Quarter'
        ELSE 'Older'
    END AS recency_bucket
FROM orders;
-- Find first and last orders per customer
SELECT
    customer_id,
    MIN(order_date) AS first_order,
    MAX(order_date) AS last_order,
    MAX(order_date) - MIN(order_date) AS customer_lifespan
FROM orders
GROUP BY customer_id;

Practical Examples

Monthly Revenue Report

-- Generate a monthly revenue report with growth calculation
WITH monthly AS (
    SELECT
        DATE_TRUNC('month', order_date) AS month,
        SUM(amount) AS revenue
    FROM orders
    GROUP BY DATE_TRUNC('month', order_date)
)
SELECT
    month,
    revenue,
    LAG(revenue) OVER (ORDER BY month) AS prev_month,
    ROUND(
        (revenue - LAG(revenue) OVER (ORDER BY month))
        / LAG(revenue) OVER (ORDER BY month) * 100, 1
    ) AS growth_pct
FROM monthly
ORDER BY month;

Business Day Calculator

-- Count business days between two dates (excluding weekends)
SELECT
    order_id,
    order_date,
    ship_date,
    EXTRACT(DAY FROM AGE(ship_date, order_date))
        - (EXTRACT(DOW FROM ship_date) - EXTRACT(DOW FROM order_date)) / 7
        AS approx_business_days
FROM orders
WHERE ship_date IS NOT NULL;

Summary


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement