SQL Examples

SQL Date Calculations

SQL Date Calculations

Date calculations with date functions and INTERVAL compute time differences.

Understanding SQL Date Functions

SQL provides a variety of functions to handle date and time calculations, which are crucial for data analysis, reporting, and application development. These functions enable you to manipulate dates, calculate time intervals, and perform date arithmetic.

Using the CURRENT_DATE Function

The CURRENT_DATE function returns the current date. This can be useful when you need to compare or calculate dates relative to today.

Adding and Subtracting Dates with INTERVAL

The INTERVAL keyword allows you to add or subtract a specified time period from a date. This is useful for calculating future or past dates.

Calculating the Difference Between Dates

To find the number of days between two dates, you can simply subtract one date from another. This operation returns the difference in days.

Working with the DATE_ADD and DATE_SUB Functions

Besides using the INTERVAL keyword, SQL also provides the DATE_ADD and DATE_SUB functions for date arithmetic, which offer a more readable syntax for some users.

Extracting Parts of a Date

SQL also provides functions to extract specific parts of a date, such as the year, month, or day. This can be useful for reports and data analysis.

Formatting Dates with the DATE_FORMAT Function

The DATE_FORMAT function allows you to format dates in various ways. This is particularly useful for displaying dates in a user-friendly format.