Cover Image for MySQL Extract
132 views

MySQL Extract

The MySQL EXTRACT() function is used to extract a part of a date or time value, such as the year, month, day, hour, minute, or second. It can be applied to various date and time data types, including DATE, TIME, DATETIME, and TIMESTAMP. The syntax of the EXTRACT() function is as follows:

EXTRACT(field FROM source)
  • field: Specifies the part of the date or time to extract, such as ‘YEAR’, ‘MONTH’, ‘DAY’, ‘HOUR’, ‘MINUTE’, or ‘SECOND.’
  • source: The date or time value from which you want to extract the specified part.

Here are some examples of how to use the EXTRACT() function:

  1. Extract Year from a Date:
    To extract the year from a DATE value, you can use the following query:
   SELECT EXTRACT(YEAR FROM '2023-10-15');

This will return 2023.

  1. Extract Month from a Date:
    To extract the month from a DATE value, you can use the following query:
   SELECT EXTRACT(MONTH FROM '2023-10-15');

This will return 10.

  1. Extract Hour from a DateTime:
    To extract the hour from a DATETIME value, you can use the following query:
   SELECT EXTRACT(HOUR FROM '2023-10-15 14:30:45');

This will return 14.

  1. Extract Second from a Time:
    To extract the second from a TIME value, you can use the following query:
   SELECT EXTRACT(SECOND FROM '14:30:45');

This will return 45.

You can use the EXTRACT() function in combination with other SQL clauses and functions to retrieve specific date and time components for various purposes, such as reporting or data analysis.

Keep in mind that the available date and time fields and the behavior of the EXTRACT() function may vary depending on your MySQL version, so it’s important to refer to the official documentation for the specific version you are using.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS