The HOUR function in MySQL is used to extract the hour from a given time or datetime expression. It returns an integer value representing the hour of the specified time.
Syntax
Here’s the basic syntax of the HOUR function:
HOUR(time)
time: This is the time or datetime value from which you want to extract the hour.
Examples
Let’s look at some examples to understand how the HOUR function works:
Extracting the hour from a datetime value
SELECT HOUR('2024-01-01 15:30:45');
This query will return 15, as it extracts the hour from the specified datetime value.
Extracting the hour from a time value
SELECT HOUR('08:45:30');
This query will return 8, as it extracts the hour from the specified time value.
Using the HOUR function in a WHERE clause
SELECT * FROM orders WHERE HOUR(order_date) >= 12;
This query retrieves records from the “orders” table where the hour of the “order_date” is greater than or equal to 12.
Keep in mind that the HOUR function returns values in the range from 0 to 23, as hours are typically represented in a 24-hour format in MySQL.
In summary, the HOUR function is a useful tool when you need to work specifically with the hour component of a time or datetime expression in MySQL.