EXTRACT¶
The EXTRACT function in SQL is used to retrieve a specific datetime field from a date, time, or interval.
Syntax¶
field: The datetime field to extract. Valid fields includeYEAR,MONTH,DAY,HOUR,MINUTE,SECOND.source: The date, time, or interval value from which the datetime field is to be extracted.
Usage¶
Here are examples of how EXTRACT can be used to pull specific datetime components from various types of datetime and interval data.
-
Extracting the
This returnsHOURfrom aTIMESTAMP:13. -
Extracting the
This returnsYEARfrom aTIMESTAMP:2016. -
Extracting the
This returnsSECONDfrom aTIMEvalue:28. -
Extracting the
This returnsDAYfrom aDATEvalue:6. -
Extracting from
INTERVALdata:These returnSELECT EXTRACT(YEAR FROM INTERVAL '3' YEAR) as extract; SELECT EXTRACT(MINUTE FROM INTERVAL '7' MINUTE) as extract;3and7, respectively.
Note that the EXTRACT function expects the source to be of a compatible datetime or interval type. Using a value of an incompatible type, such as a number or a string that cannot be interpreted as a datetime, will result in an error.