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
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
Date Literals
Write date values using the DATE keyword followed by a quoted string:
Timestamp Literals
Write timestamp values using the TIMESTAMP keyword:
Comparison
Choosing between DATE and TIMESTAMP affects storage, query complexity, and what questions you can answer with your data.
Date vs Timestamp
- Calendar day only (2024-03-15)
- Uses less storage (4 bytes)
- Simpler to query and compare
- Best for birth dates, holidays
- Specific moment (14:30:45)
- More storage (8-12 bytes)
- Precision for event sequencing
- Best for logs, transactions
> Complete this query to extract just the date from a timestamp column.
SELECT order_id, (order_time AS ) AS order_date FROM orders
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
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.
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:
Filtering Recent Data
CURRENT_DATE is most commonly used in WHERE clauses to filter for today's records.
Building Dynamic Reports
You can include CURRENT_DATE in the SELECT clause to label reports with their generation date.
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.
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
When do you need CURRENT_DATE versus CURRENT_TIMESTAMP?
> Complete this query to find all orders placed today.
SELECT order_id, total FROM orders WHERE order_date
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
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
Practical Applications
CURRENT_TIMESTAMP is essential for audit trails, logging, and calculating time-based windows.
Recording Event Times
Recent Activity Queries
Combine CURRENT_TIMESTAMP with interval arithmetic to find records within a time window.
> 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 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()
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
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.
Subtracting Time
DATE_ADD works for subtraction too by using negative numbers.
Negative Amounts
Best Practices
DATE_ADD is essential for business logic involving deadlines, schedules, and time-based calculations.
When to Use DATE_ADD()
> Complete this query to find the date 30 days from today.
SELECT (, , ) AS due_date
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()
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
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.
Practical Applications
DATE_DIFF powers many business metrics including age calculations, tenure tracking, and SLA monitoring.
Age Calculations
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:
Best Practices
DATE_DIFF is fundamental to analytics and operational reporting.
When to Use DATE_DIFF()
- 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
- 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
- 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
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.
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.
> 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.DATE stores calendar days (YYYY-MM-DD); TIMESTAMP stores moments (with time)CURRENT_DATE returns today; CURRENT_TIMESTAMP returns now with timeDATE_ADD(unit, amount, date) calculates future/past dates; negative amounts subtractDATE_DIFF(unit, start, end) measures complete units between two datesWhy
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
- 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?
- 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
- 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
- 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.
- 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