The HOUR() function in MySQL is used to extract the hour portion from a given time or datetime expression. It returns an integer value representing the hour (in 24-hour format, ranging from 0 to 23).
Syntax
HOUR(time)
Parameters
time: A valid time or datetime expression from which the hour will be extracted.
Returns
- An integer between 0 and 23.
- If the input is
NULLor an invalid time, the function returnsNULL.
Examples
-
Extract hour from a time value
SELECT HOUR('14:35:59') AS Hour;Result:
14 -
Extract hour from a datetime value
SELECT HOUR('2023-12-23 18:45:00') AS Hour;Result:
18 -
Using with a column in a table Suppose you have a table
eventswith a columnevent_time(datatypeDATETIME):SELECT event_time, HOUR(event_time) AS EventHour FROM events; -
Using with CURRENT_TIME or NOW()
SELECT HOUR(NOW()) AS CurrentHour;Result: (Returns the current hour of the server time.)
-
Invalid or NULL input
SELECT HOUR('Invalid Time') AS Hour, HOUR(NULL) AS HourWithNull;Result:
NULL,NULL
Use Case
The HOUR() function is commonly used when you need to group or filter records by the hour part of a time or datetime column, such as analyzing hourly trends in data.
For example:
SELECT HOUR(event_time) AS Hour, COUNT(*) AS EventCount
FROM events
GROUP BY HOUR(event_time);
No comments:
Post a Comment