What kind of compound units can be used in MySQL EXTRACT() function?


MySQL EXTRACT() function can use following compound units −

  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • HOUR_MICROSECOND
  • DAY_MICROSECOND
  • MINUTE_SECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH

Some of the examples of these compound units used in EXTRACT() function are as follows −

mysql> Select EXTRACT(YEAR_MONTH from '2017-10-20');
+---------------------------------------+
| EXTRACT(YEAR_MONTH from '2017-10-20') |
+---------------------------------------+
|                             201710    |
+---------------------------------------+
1 row in set (0.00 sec)

Above query will return the year and month value from the date.

mysql> Select EXTRACT(DAY_HOUR from '2017-10-20 05:46:45');
+----------------------------------------------+
| EXTRACT(DAY_HOUR from '2017-10-20 05:46:45') |
+----------------------------------------------+
|                                         2005 |
+----------------------------------------------+
1 row in set (0.00 sec)

Above query will return the day and hour value from a date.

One thing we must have to take into consideration that the above-mentioned compound units are a complete set of values i.e. if we will use DAY_MINUTE, MySQL returns the DAY, HOUR and MINUTE. It means that any value that would normally be expected is filled in between a start and end unit.

For example, the below query is using DAY_MICROSECOND compound unit and MySQL returns the DAY, HOUR, MINUTE, SECOND and MICROSECOND. It means that the values of HOUR, MINUTE and SECOND are filled in between DAY and MICROSECOND.

mysql> Select EXTRACT(DAY_MICROSECOND from '2017-10-22 05:52:45.102356');
+---------------------------------------------------------------------------+
| EXTRACT(DAY_MICROSECOND from '2017-10-22 05:52:45.102356')                |
+---------------------------------------------------------------------------+
|                                                            22055245102356 |
+---------------------------------------------------------------------------+
1 row in set (0.00 sec)

Updated on: 20-Jun-2020

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements