π Overview In this exercise, we explore the use of SQL DateTime functions to work with date and time data. You'll learn how to extract, filter, and manipulate date-related fields from a database using SQL.
These techniques are particularly useful when analyzing time-based data such as sales, revenue trends, or customer activity.
By the end of this exercise, you will be able to:
β Measure the period between dates and times.
β Extract specific parts of a DateTime column (e.g., year, month).
β Filter records using logical and comparison operators on DateTime fields.
-
SQL Dialect: SQLite (Compatible with other SQL engines, but minor differences may exist)
-
Sample Database:
chinook.db
(A small demo database with tables such asinvoices
,customers
, andemployees
) -
Environment: Local environment (Jupyter Notebook, SQLite browser, or compatible SQL IDE)
-
Calculate monthly or yearly revenue
-
Find the age of employees when hired
-
Analyze customer purchases over time
-
Filter records based on date ranges
- Extracting Year from Date:
SELECT
SUBSTR(InvoiceDate, 1, 4) AS Year,
ROUND(SUM(Total), 2) AS Revenue
FROM invoices
GROUP BY Year
ORDER BY Year;
- Filtering by Date:
SELECT *
FROM invoices
WHERE InvoiceDate >= '2010-01-01';
- Calculating Duration Between Two Dates:
SQLite does not support
DATEDIFF()
, but we can usejulianday()
:
SELECT
CustomerId,
InvoiceDate,
julianday('now') - julianday(InvoiceDate) AS Days_Since_Invoice
FROM invoices;
-
Use SUBSTR() or strftime() to extract year/month/day.
-
For SQLite: use julianday() to compute date differences.
-
Always ensure your dates are in ISO format (YYYY-MM-DD) for best results.
-
SQLite Date & Time Functions
-
ExploreAI Academy SQL Curriculum
π sql_datetime_functions/
β
βββ chinook.db # SQLite sample database
βββ datetime_exercise.sql # SQL queries for the exercise
βββ README.md # This file