DataBolt

All Lessons

Introduction to SQL
SQL Lesson 1: Your Sample Database
SQL Lesson 2: SELECT — Reading data
SQL Lesson 3: WHERE — Filtering rows
SQL Lesson 4: AND, OR, NOT
SQL Lesson 5: BETWEEN, IN, LIKE
SQL Lesson 6: NULL — The Mystery Value
SQL Lesson 7: ORDER BY
SQL Lesson 8: LIMIT & OFFSET
SQL Lesson 9: Aggregate Functions
SQL Lesson 10: GROUP BY
SQL Lesson 11: HAVING
SQL Lesson 12: INNER JOINs
SQL Lesson 13: LEFT JOINs
SQL Lesson 14: RIGHT JOINs
SQL Lesson 15: SELF JOINs
SQL Lesson 16: UNION JOINs
SQL Lesson 17: Joining Multiple Tables
SQL Lesson 18: Subqueries
SQL Lesson 19: CTEs (WITH)
SQL Lesson 20: CASE Statements
SQL Lesson 21: Window Functions
SQL Lesson 22: String Functions
SQL Lesson 23: Date & Time Functions
SQL Lesson 24: INSERT, UPDATE, DELETE
SQL Lesson 25: CREATE TABLE & DDL
SQL Lesson 26: Indexes & Performance
SQL Lesson 27: Transactions & ACID
SQL Lesson 28: SQL Execution Order
SQL Lesson 29: 50 Practice Problems

CHAPTER 24

Data & Time Functions

Working with dates - extraction, arithmetic, formatting.

IN THIS CHAPTER

  • Getting current date and time
  • Extracting year, month, day from a date
  • Calculating differences between dates
  • Adding and subtracting intervals
  • Filtering by date ranges

FunctionReturnsExample
NOW()Current date + time2024-03-29 14:30:00
CURDATE()Current date only2024-03-29
YEAR(date)Year integerYEAR('2024-03-29') → 2024
MONTH(date)Month integerMONTH('2024-03-29') → 3
DAY(date)Day integerDAY('2024-03-29') → 29
MONTHNAME(date)Month nameMONTHNAME('2024-03-29') → March
DAYNAME(date)Weekday nameDAYNAME('2024-03-29') → Friday
DATEDIFF(d1,d2)Days between datesDATEDIFF('2024-12-31','2024-01-01') → 365
TIMESTAMPDIFF(unit,d1,d2)Difference in any unitTIMESTAMPDIFF(YEAR, dob, CURDATE())
DATE_ADD(date, INTERVAL n)Add to a dateDATE_ADD('2024-01-01', INTERVAL 30 DAY)
DATE_SUB(date, INTERVAL n)Subtract from a dateDATE_SUB(CURDATE(), INTERVAL 90 DAY)

Example

Order from the last 90 days

SELECT order_id, order_date, total
FROM orders
WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY);

Exercise 👇

Exercise:

Tasks

1.👉Show each employee's name along with the year they were hired.
2.Display the month number in which each employee was hired.
3.Display the month name in which each employee was hired.
4.Add 7 days to each employee's hire date and display the new date.
5.Calculate how many days each employee has worked till today.
Stuck? Read this task's