SQL Date Calculations
What is Date Calculations in SQL?
Also you can perform various date calculations using built-in functions to manipulate and work with date and time values.
Common date calculations:
Adding or Subtracting Days:
Use the DATE_ADD or DATE_SUB functions to add or subtract days from a date:
-- Adding 3 days to the current date
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 3 DAY) AS future_date;
-- Subtracting 1 day from the current date
SELECT DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY) AS past_date;
Extracting Components of a Date:
Use the YEAR, MONTH, and DAY functions to extract the year, month, and day components from a date:
SELECT
YEAR(some_date_column) AS year,
MONTH(some_date_column) AS month,
DAY(some_date_column) AS day
FROM your_table;
Formatting Dates:
Use the DATE_FORMAT function to format date values into a specific format:
SELECT
some_date_column,
DATE_FORMAT(some_date_column, '%Y-%m-%d') AS formatted_date
FROM your_table;
Calculating Date Differences:
Use the DATEDIFF function to calculate the difference between two dates in days:
SELECT
DATEDIFF(end_date_column, start_date_column) AS days_difference
FROM your_table;
Calculating Age:
Use the TIMESTAMPDIFF function to calculate the age in years, months, or days:
SELECT
TIMESTAMPDIFF(YEAR, birth_date_column, CURRENT_DATE) AS age_in_years,
TIMESTAMPDIFF(MONTH, birth_date_column, CURRENT_DATE) AS age_in_months,
TIMESTAMPDIFF(DAY, birth_date_column, CURRENT_DATE) AS age_in_days
FROM your_table;
Tips:
- Be aware of the date format used in your database, as it might affect date calculations.
- Understand the data types and functions supported by your specific database system (e.g., MySQL, PostgreSQL, SQL Server).
- Pay attention to time zones if your dates include time components.