Working with dates in SQL involves several functions and operators for manipulating, formatting, and extracting date and time information. Here are some common operations you can perform with dates in SQL:
Current Date and Time:
GETDATE()
or CURRENT_TIMESTAMP
: Returns the current date and time.Example:
SELECT GETDATE(); -- Returns the current date and time
Date Functions:
DATEADD(interval, number, date)
: Adds a specified number of intervals (such as days, months, years) to a date.DATEDIFF(interval, start_date, end_date)
: Returns the difference between two dates in terms of the specified interval.DATEPART(interval, date)
: Extracts a specific part of a date (such as year, month, day).Example:
SELECT DATEADD(DAY, 7, '2022-01-01'); -- Adds 7 days to January 1, 2022
SELECT DATEDIFF(YEAR, '1990-01-01', '2022-01-01'); -- Returns the difference in years between two dates
SELECT DATEPART(MONTH, '2022-04-14'); -- Returns the month component of the date
Date Formatting:
CONVERT(data_type, expression, style)
: Converts a date/time value to a specified format.FORMAT(date, format)
: Formats a date/time value using