Dates: Beginner

Netflix coordinates content releases across 190 countries, and getting a premiere date wrong by even a single day can mean millions of subscribers in one region see spoilers before others have access, destroying the opening-weekend viewership spike that the company uses to justify content budgets. Every scheduled release, regional licensing window, and content expiry in Netflix's catalog is tracked with date arithmetic in SQL, from calculating days until a show goes live to measuring how long a title has been available in each market. The SQL date functions in this lesson are the same building blocks that power those calculations at global scale. You will learn how databases store dates, how to get the current date dynamically, and how to do basic date arithmetic.

DATE vs TIMESTAMP data types

Daily Life
Interviews

Choose the right type for time data

SQL provides two core temporal types: DATE for calendar days and TIMESTAMP for precise moments. Choosing between them affects storage, query complexity, and what questions you can answer with your data.

DATE stores only the calendar date in YYYY-MM-DD format. No time component exists. It uses less storage and is simpler to compare. TIMESTAMP stores both date and time, providing the precision needed for event sequencing and duration calculations.

Date and Timestamp Literals

SQL uses specific syntax to write date and timestamp values directly in queries.
//

Date Literals

Write date values using the DATE keyword followed by a quoted string:

1SELECT
2 DATE '2024-03-15' AS event_date
3FROM events
Result
event_date
2024-03-15
The ISO 8601 format (YYYY-MM-DD) is universally supported. Always use this format for date literals to avoid ambiguity between American (MM/DD) and European (DD/MM) conventions.
//

Timestamp Literals

Write timestamp values using the TIMESTAMP keyword:

1SELECT
2 TIMESTAMP '2024-03-15 14:30:45' AS event_time
3FROM events
Result
event_time
2024-03-15 14:30:45

Comparison

Choosing between DATE and TIMESTAMP affects storage, query complexity, and what questions you can answer with your data.

//

Date vs Timestamp

Here is a side-by-side comparison of the two core temporal types.
DATE
  • Calendar day only (2024-03-15)
  • Uses less storage (4 bytes)
  • Simpler to query and compare
  • Best for birth dates, holidays
TIMESTAMP
  • Specific moment (14:30:45)
  • More storage (8-12 bytes)
  • Precision for event sequencing
  • Best for logs, transactions
Which type would you use to track when users perform actions?
Casting to DATE discards the time component. You lose the ability to determine the order of events within a day or measure how long actions took. This is only appropriate when daily granularity is sufficient.
1SELECT
2 user_id,
3 action,
4 CAST(action_time AS DATE) AS action_date
5FROM user_actions

> Complete this query to extract just the date from a timestamp column.

SELECT
  order_id,
  ___(order_time AS ___) AS order_date
FROM orders
DATE
TIMESTAMP
CAST

DATE stores only year, month, and day. If you need to compare timestamps to CURRENT_DATE, cast the timestamp to DATE first so the time component does not prevent matches.

TIMESTAMP has more storage overhead than DATE. For columns that only ever need day-level precision, using the DATE type saves space and simplifies comparisons.

Choosing the right type at table creation prevents subtle bugs later. A TIMESTAMP column used for dates will cause every date comparison to include implicit time boundaries.

CURRENT_DATE & CURRENT_TIME

Daily Life
Interviews

Reference today and right now in queries

CURRENT_DATE returns today's date according to the database server. It has no time component, giving you just the calendar date. This function takes no arguments and returns a date value that changes daily.

The syntax is simply CURRENT_DATE with no parentheses. It evaluates to the current date at the moment the query runs. The value remains constant throughout a single query execution.

This function is your go-to tool for queries that need to reference "today" without hardcoding dates.

CURRENT_DATE Usage Patterns

These patterns show the most common ways to use CURRENT_DATE in real queries.

//

Basic Usage

CURRENT_DATE enables dynamic queries that always reference today:

1SELECT
2 CURRENT_DATE AS today
3FROM orders
Result
today
2024-03-15
The result reflects whatever date the query executes. Running this query tomorrow returns tomorrow's date. This dynamic behavior is essential for queries that need to stay current without manual updates.
//

Filtering Recent Data

CURRENT_DATE is most commonly used in WHERE clauses to filter for today's records.

1SELECT
2 order_id,
3 order_date,
4 total
5FROM orders
6WHERE order_date = CURRENT_DATE
Result
order_idorder_datetotal
105422024-03-15156.99
105432024-03-1589.50
105442024-03-15234.00
This query finds all orders placed today. The filter automatically adjusts as days pass. Tomorrow, the same query returns only tomorrow's orders.
//

Building Dynamic Reports

You can include CURRENT_DATE in the SELECT clause to label reports with their generation date.

1SELECT
2 'Daily Sales Report' AS report_name,
3 CURRENT_DATE AS report_date,
4 COUNT(*) AS orders_today,
5 SUM(total) AS revenue_today
6FROM orders
7WHERE order_date = CURRENT_DATE
Result
report_namereport_dateorders_todayrevenue_today
Daily Sales Report2024-03-15478432.50
The report always shows today's data without requiring parameter changes. Scheduled reports using this pattern stay current automatically.
TIP
CURRENT_DATE returns the date in the database server's timezone. If your users span multiple timezones, "today" might be different for users in Tokyo versus New York.
//

When to Use CURRENT_DATE

CURRENT_DATE appears in many common data workflows.

Daily reports
Daily reports
Filtering today's records in dashboards and automated reports
Data pipelines
Data pipelines
Setting default date values and creating partition keys for daily loads
Age calculations
Age calculations
Building age calculations from birth dates and event distances

CURRENT_TIME

While less common than CURRENT_DATE, this function is useful for time-of-day logic.

//

Time Function

CURRENT_TIME returns the current time of day without the date component. It provides just the hours, minutes, and seconds according to the database server's clock.

//

Time-Based Filtering

You can filter records based on time-of-day comparisons.
1SELECT
2 event_name,
3 event_time
4FROM scheduled_events
5WHERE event_time > CURRENT_TIME
Result
event_nameevent_time
Team standup15:00:00
Client call16:30:00
End of day report17:00:00
This query finds events scheduled later today. The comparison uses only time values, ignoring the date. This pattern works for daily recurring schedules.

When do you need CURRENT_DATE versus CURRENT_TIMESTAMP?

CURRENT_DATE returns only today's date with no time component. It is ideal for day-level comparisons like finding all orders placed today or checking if a deadline has passed.
1SELECT
2 order_id,
3 total
4FROM orders
5WHERE order_date = CURRENT_DATE

> Complete this query to find all orders placed today.

SELECT
  order_id,
  total
FROM orders
WHERE order_date ___ ___
CURRENT_DATE
CURRENT_TIME
>
=

CURRENT_DATE is evaluated once at the start of a query and remains constant throughout. Even if a query runs across midnight, every row sees the same date value.

CURRENT_TIME without a date is rarely used in practice. Most time-of-day filtering pairs the time with a date, making CURRENT_TIMESTAMP the more common choice for dynamic queries.

The database server timezone determines what CURRENT_DATE returns. For applications with global users, configure the server to UTC so all queries have a consistent reference point.

CURRENT_TIMESTAMP function

Daily Life
Interviews

Capture exact moments with timestamps

CURRENT_TIMESTAMP returns the current date and time as a single timestamp value. It provides the complete moment, combining both calendar date and precise time. This is the most commonly used function for capturing "right now" in data pipelines.

CURRENT_TIMESTAMP requires no arguments and returns the complete date-time value.

Using CURRENT_TIMESTAMP

These examples show how CURRENT_TIMESTAMP appears in practical queries.

//

Basic Usage

Here is the simplest way to retrieve the current timestamp.
1SELECT
2 CURRENT_TIMESTAMP AS exact_moment
3FROM logs
Result
exact_moment
2024-03-15 14:30:45.123
The result captures the exact moment the query executed. This precision is essential for audit trails, event logging, and any situation where knowing the precise time matters.

Practical Applications

CURRENT_TIMESTAMP is essential for audit trails, logging, and calculating time-based windows.

//

Recording Event Times

Adding timestamps to records creates an audit trail of when events occurred.
1SELECT
2 user_id,
3 action,
4 CURRENT_TIMESTAMP AS recorded_at
5FROM user_actions
Result
user_idactionrecorded_at
1001login2024-03-15 14:30:45
1002view_page2024-03-15 14:30:45
1003purchase2024-03-15 14:30:45
Each record gets the same timestamp within a single query. This is intentional, ensuring consistency within a transaction.
//

Recent Activity Queries

Combine CURRENT_TIMESTAMP with interval arithmetic to find records within a time window.

1SELECT
2 user_id,
3 last_login
4FROM users
5WHERE last_login >= CURRENT_TIMESTAMP - INTERVAL '24' HOUR
Result
user_idlast_login
10012024-03-15 10:20:00
10052024-03-15 08:45:30
10122024-03-14 18:30:00
This query finds users who logged in within the last 24 hours. The time window moves forward continuously, always showing the most recent 24-hour period.

> Complete this query to find users who logged in within the last 24 hours.

SELECT
  user_id,
  last_login
FROM users
WHERE last_login >= ___ - ___
INTERVAL '24' HOUR
24
CURRENT_TIMESTAMP
CURRENT_DATE

INTERVAL arithmetic is portable across most SQL engines. The CURRENT_TIMESTAMP - INTERVAL pattern is safer than hardcoding a cutoff timestamp that would require updating manually.

For very large tables, filtering with CURRENT_TIMESTAMP can prevent partition pruning if the column is not a partition key. Check your query plan to ensure the database is applying the filter efficiently.

CURRENT_TIMESTAMP is evaluated once per query. Subtracting an interval from it inside a WHERE clause creates a fixed window for that query execution, ensuring consistent results across all returned rows.

DATE_ADD()

Daily Life
Interviews

Calculate future and past dates

DATE_ADD adds a specified time interval to a date or timestamp. It allows you to calculate future dates, deadlines, expiration times, and any temporal offset from a starting point.

The syntax is DATE_ADD(unit, amount, date). The unit specifies what to add (day, month, year, hour, etc.). The amount is how many units to add. Negative amounts subtract instead of add.

DATE_ADD handles the complexity of calendar math, including month lengths and leap years.

Adding Time Intervals

DATE_ADD supports multiple time units, each suited to different scheduling needs.

//

Adding Days

The most common use case is adding days to calculate due dates or deadlines:
1SELECT
2 invoice_id,
3 invoice_date,
4 DATE_ADD('day', 30, invoice_date) AS due_date
5FROM invoices
Result
invoice_idinvoice_datedue_date
INV-0012024-03-012024-03-31
INV-0022024-03-152024-04-14
INV-0032024-03-202024-04-19

DATE_ADD('day', 30, invoice_date) adds 30 days to each invoice date. The result crosses month boundaries automatically. March 15 plus 30 days correctly becomes April 14.

//

Different Time Units

DATE_ADD supports various time units, letting you add days, months, or years depending on your needs.

Adding 7 days calculates one week from today. Useful for weekly deadlines or scheduling.
1SELECT
2 DATE_ADD('day', 7, CURRENT_DATE) AS next_week

Subtracting Time

DATE_ADD works for subtraction too by using negative numbers.

//

Negative Amounts

Use negative amounts to subtract time and look backward:
1SELECT
2 DATE_ADD(
3 'day',
4 - 7,
5 CURRENT_DATE
6 ) AS one_week_ago,
7 DATE_ADD(
8 'month',
9 - 3,
10 CURRENT_DATE
11 ) AS three_months_ago,
12 DATE_ADD(
13 'year',
14 - 1,
15 CURRENT_DATE
16 ) AS one_year_ago
17FROM orders
Result
one_week_agothree_months_agoone_year_ago
2024-03-082023-12-152023-03-15
Negative values move backward in time. This is essential for historical analysis, comparing year-over-year metrics, and calculating retention windows.
TIP
Adding months to dates near month-end can produce unexpected results. January 31 plus one month might give February 28 or March 2 depending on the database. Test edge cases in your specific environment.

Best Practices

DATE_ADD is essential for business logic involving deadlines, schedules, and time-based calculations.

//

When to Use DATE_ADD()

Here are the most common scenarios where date arithmetic is needed.
Due datesExpiration timesHistorical lookbackRecurring eventsForecast dates
Due dates
Deadlines
Calculate future due dates
Expiration times
Expirations
Set time-based cutoffs
Historical lookback
Lookbacks
Query past date ranges
Recurring events
Scheduling
Generate repeat intervals
Forecast dates
Forecasting
Project future outcomes

> Complete this query to find the date 30 days from today.

SELECT
  ___(___, ___, ___) AS due_date
DATE_ADD
'day'
CURRENT_DATE
'month'
30

DATE_ADD with CURRENT_DATE creates self-updating deadlines. A query for "30 days from today" always reflects the current date, eliminating the need to update hardcoded deadline values.

When adding months, DATE_ADD handles varying month lengths automatically. Adding one month to January 31 gives February 28 or 29, not an error or an overflow into March.

Combine DATE_ADD with CURRENT_DATE in WHERE clauses to build rolling windows. For example, filtering where due_date between today and today plus 7 days finds items due this week.

DATE_DIFF()

Daily Life
Interviews

Measure time between two events

DATE_DIFF calculates the difference between two dates or timestamps in a specified unit. It returns an integer representing how many complete units separate the two points in time.

The syntax is DATE_DIFF(unit, start_date, end_date). The unit specifies the measurement (day, month, year, hour, etc.). Positive values mean end_date is later; negative values mean end_date is earlier.

DATE_DIFF answers questions about time elapsed between events or from a reference point.

Calculating Time Differences

DATE_DIFF returns the number of complete units between two dates, with the result sign indicating direction.

//

Calculating Days Between

The most common use case is calculating the number of days between two events:
1SELECT
2 order_id,
3 order_date,
4 ship_date,
5 DATE_DIFF(
6 'day',
7 order_date,
8 ship_date
9 ) AS days_to_ship
10FROM orders
Result
order_idorder_dateship_datedays_to_ship
10012024-03-012024-03-043
10022024-03-052024-03-061
10032024-03-102024-03-188

DATE_DIFF('day', order_date, ship_date) counts complete days between ordering and shipping. Order 1001 took 3 days. Order 1003 took 8 days, potentially flagging a fulfillment issue.

//

Different Time Units

DATE_DIFF works with various time units, letting you measure differences in days, months, or hours.

Days between hire date and today shows employee tenure. Useful for anniversary calculations.
1SELECT
2 DATE_DIFF(
3 'day',
4 hire_date,
5 CURRENT_DATE
6 ) AS days_employed
7FROM employees

Practical Applications

DATE_DIFF powers many business metrics including age calculations, tenure tracking, and SLA monitoring.

//

Age Calculations

One of the most common uses is calculating ages from birth dates.
1SELECT
2 user_id,
3 birth_date,
4 DATE_DIFF(
5 'year',
6 birth_date,
7 CURRENT_DATE
8 ) AS age
9FROM users
Result
user_idbirth_dateage
10011990-05-2033
10021985-11-0838
10032000-03-0124
The year difference gives approximate age. For exact age that accounts for whether the birthday has passed this year, additional logic is needed, but year difference covers most use cases.
TIP
DATE_DIFF subtracts start_date from end_date. If you swap them, you get the negative result. Convention is (unit, earlier_date, later_date) for positive results.
//

SLA Metrics

DATE_DIFF measures operational performance. An SLA defines the maximum acceptable response time that a service promises to meet:

1SELECT
2 ticket_id,
3 created_at,
4 resolved_at,
5 DATE_DIFF(
6 'hour',
7 created_at,
8 resolved_at
9 ) AS resolution_hours
10FROM support_tickets
Result
ticket_idcreated_atresolved_atresolution_hours
T0012024-03-15 09:002024-03-15 14:305
T0022024-03-14 10:002024-03-16 16:0054
T0032024-03-13 15:002024-03-14 09:0018
This query calculates how many hours each ticket took to resolve. With a 24-hour SLA, tickets T001 (5 hours) and T003 (18 hours) met the target, while T002 (54 hours) exceeded it.

Best Practices

DATE_DIFF is fundamental to analytics and operational reporting.

//

When to Use DATE_DIFF()

These are the most common scenarios where calculating time differences is essential.
DATE_DIFF USE CASES
  • Measuring time between events (order to delivery)
  • Calculating user tenure or subscription age
  • Tracking SLA compliance and response times
  • Building cohort analysis based on signup age
  • Computing age from birth dates
With these use cases in mind, here are the guidelines for working with dates effectively.
Do
  • Use DATE type when time-of-day is irrelevant
  • Use TIMESTAMP when precise moments matter
  • Store dates in UTC and convert for display
  • Use CURRENT_DATE/CURRENT_TIMESTAMP for dynamic queries
  • Document your timezone assumptions
Don't
  • Store dates as strings unless you have no choice
  • Assume all systems share the same timezone
  • Ignore month-boundary edge cases with DATE_ADD
  • Confuse DATE_DIFF argument order
  • Use hardcoded date literals in production queries

> Complete this query to calculate how many days each order took to ship.

SELECT
  order_id,
  ___(
    ___,
    ___,
    ___
    ) AS days_to_ship
FROM orders
'day'
order_date
'month'
DATE_DIFF
ship_date

DATE_DIFF counts only complete units. If an order was placed at 11 PM and shipped at 1 AM the next day, DATE_DIFF in days returns 1 even though only 2 hours elapsed.

Swapping the start and end arguments produces a negative result. Always pass the earlier date as the second argument and the later date as the third to get a positive difference.

DATE_DIFF is the foundation for SLA tracking, cohort analysis, and retention calculations. Mastering the argument order and unit selection unlocks a wide range of business metrics.

PUTTING IT ALL TOGETHER

> You are a data analyst at Notion building a monthly active user report grouped by subscription signup month for the growth team. The report must always reflect the rolling 30 days without manual date edits each time it runs.

DATE vs TIMESTAMP determines whether you group by signup day alone or capture the exact sign-up moment.
CURRENT_DATE anchors the rolling 30-day window so the WHERE clause updates automatically on every run.
DATE_ADD() subtracts 30 days from today to define the start of the active user window dynamically.
DATE_DIFF() calculates each user's days since signup, enabling tenure-based segmentation within the report.
KEY TAKEAWAYS
DATE stores calendar days (YYYY-MM-DD); TIMESTAMP stores moments (with time)
CURRENT_DATE returns today; CURRENT_TIMESTAMP returns now with time
DATE_ADD(unit, amount, date) calculates future/past dates; negative amounts subtract
DATE_DIFF(unit, start, end) measures complete units between two dates
Dates use less storage; timestamps provide precision for event sequencing
Always consider timezone implications for multi-region systems
Test date arithmetic near month boundaries for edge case handling
Dynamic date functions make queries self-updating without manual changes

Why

Why "yesterday" is harder than you think

Category
SQL
Difficulty
beginner
Duration
26 minutes
Challenges
0 hands-on challenges

Topics covered: DATE vs TIMESTAMP data types, CURRENT_DATE & CURRENT_TIME, CURRENT_TIMESTAMP function, DATE_ADD(), DATE_DIFF()

Lesson Sections

  1. DATE vs TIMESTAMP data types (concepts: sqlDateVsTimestamp)

    Date and Timestamp Literals SQL uses specific syntax to write date and timestamp values directly in queries. Date Literals The ISO 8601 format (YYYY-MM-DD) is universally supported. Always use this format for date literals to avoid ambiguity between American (MM/DD) and European (DD/MM) conventions. Timestamp Literals Comparison Date vs Timestamp Here is a side-by-side comparison of the two core temporal types. Which type would you use to track when users perform actions?

  2. CURRENT_DATE & CURRENT_TIME (concepts: sqlCurrentDate)

    This function is your go-to tool for queries that need to reference "today" without hardcoding dates. CURRENT_DATE Usage Patterns Basic Usage The result reflects whatever date the query executes. Running this query tomorrow returns tomorrow's date. This dynamic behavior is essential for queries that need to stay current without manual updates. Filtering Recent Data This query finds all orders placed today. The filter automatically adjusts as days pass. Tomorrow, the same query returns only tomor

  3. CURRENT_TIMESTAMP function

    Using CURRENT_TIMESTAMP Basic Usage Here is the simplest way to retrieve the current timestamp. The result captures the exact moment the query executed. This precision is essential for audit trails, event logging, and any situation where knowing the precise time matters. Practical Applications Recording Event Times Adding timestamps to records creates an audit trail of when events occurred. Each record gets the same timestamp within a single query. This is intentional, ensuring consistency withi

  4. DATE_ADD() (concepts: sqlDateAdd)

    Adding Time Intervals Adding Days The most common use case is adding days to calculate due dates or deadlines: Different Time Units Subtracting Time Negative Amounts Use negative amounts to subtract time and look backward: Negative values move backward in time. This is essential for historical analysis, comparing year-over-year metrics, and calculating retention windows. Best Practices When to Use DATE_ADD() Here are the most common scenarios where date arithmetic is needed.

  5. DATE_DIFF() (concepts: sqlDateDiff)

    Calculating Time Differences Calculating Days Between The most common use case is calculating the number of days between two events: Different Time Units Practical Applications Age Calculations One of the most common uses is calculating ages from birth dates. The year difference gives approximate age. For exact age that accounts for whether the birthday has passed this year, additional logic is needed, but year difference covers most use cases. SLA Metrics This query calculates how many hours ea