SQL Date and Time
SQL provides several data types for working with date and time values. The most commonly used data types for date and time are:
DATE
: stores a date in the format 'YYYY-MM-DD'.TIME
: stores a time in the format 'HH:MI:SS'.DATETIME
orTIMESTAMP
: stores both date and time in the format 'YYYY-MM-DD HH:MI:SS'.
You can use these data types to store and retrieve date and time values in SQL queries. For example, the following SQL statement selects all records from a table where the hire_date
column is after January 1st, 2021:
SELECT * FROM employees WHERE hire_date > '2021-01-01';
You can also perform arithmetic operations on date and time values using SQL functions. For example, the following SQL statement selects all records from a table where the hire_date
column is less than one year ago:
SELECT * FROM employees WHERE hire_date < DATEADD(YEAR, -1, GETDATE());
In this example, we are using the DATEADD
function to subtract one year from the current date (GETDATE()
), and then comparing the result to the hire_date
column.
SQL also provides several other date and time functions, such as DATEDIFF
, DATEPART
, and DATEADD
, which allow you to manipulate date and time values in various ways. These functions can be used to calculate time differences, extract specific parts of a date or time, and perform other operations on date and time values.