Sunday, December 22, 2024

MySQL HOUR() Function

 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 NULL or an invalid time, the function returns NULL.

Examples

  1. Extract hour from a time value

    SELECT HOUR('14:35:59') AS Hour;
    

    Result: 14

  2. Extract hour from a datetime value

    SELECT HOUR('2023-12-23 18:45:00') AS Hour;
    

    Result: 18

  3. Using with a column in a table Suppose you have a table events with a column event_time (datatype DATETIME):

    SELECT event_time, HOUR(event_time) AS EventHour
    FROM events;
    
  4. Using with CURRENT_TIME or NOW()

    SELECT HOUR(NOW()) AS CurrentHour;
    

    Result: (Returns the current hour of the server time.)

  5. 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