Open In App

HOUR() Function in MySQL

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The HOUR() function in MySQL is a powerful tool for extracting the hour component from a given time or DateTime expression. Whether working with time, datetime or string values that can be interpreted as time, the HOUR() function returns the hour as an integer ranging from 0 to 23.

In this article, We will learn about the HOUR() Function in MySQL with the help of various examples and so on.

HOUR() Function in MySQL

The HOUR() function in MySQL is used to extract the hour part from a given time or datetime expression. It returns an integer representing the hour value which ranges from 0 to 23.

Syntax:

HOUR(time_expression)

Parameter:

This method accepts a parameter which is illustrated below :

  • time_expression: This can be a time, datetime, or a string that can be interpreted as a time.

Returns:

It returns the hour part for a specified time or date-time value.

Key Points:

  • The function works with both TIME and DATETIME data types.
  • If we pass a DATETIME value, HOUR() will extract the hour part from the time component.

Examples of HOUR() Function in MySQL

Example 1:

Getting the hour "9" from the specified date and time "2020-11-24 09:32:00".

SELECT HOUR("2020-11-24 09:32:00");

Output :

9

Example 2:

Getting the hour "6" from the specified time "06:12:23".

SELECT HOUR("06:12:23");

Output :

6

Example 3:

Let's consider a table named appointments that stores information about scheduled appointments, including the appointment time.

appointments Table:

appointment_idappointment_time
12024-09-03 08:30:00
22024-09-03 14:15:00
32024-09-03 19:45:00
42024-09-03 22:00:00

Query using the HOUR() Function:

Suppose we want to extract the hour from each appointment_time to determine when each appointment is scheduled.

SELECT appointment_id, HOUR(appointment_time) AS appointment_hour
FROM appointments;

Output:

appointment_idappointment_hour
18
214
319
422

In this example:

  • The HOUR() function extracts the hour part from each appointment_time.
  • The result shows the hour at which each appointment is scheduled, allowing us to analyze appointments based on the time of day.

Conclusion

The HOUR() function in MySQL is essential for time-related queries, allowing you to extract and work with the hour component of time and datetime values. This capability is particularly beneficial when analyzing data based on specific hours of the day, making it easier to manage and interpret time-based records.


Next Article
Article Tags :

Similar Reads