Lesson

MySQL HOUR() Function

10 min reading
Free Course

MySQL HOUR(): Extract the Hour From Time or Datetime Values

The HOUR() function extracts the hour component from a TIME, DATETIME, or TIMESTAMP value. For clock timestamps (DATETIME), it returns an integer from 0 to 23. For elapsed TIME durations, MySQL supports hours up to 838.

E-commerce analysts use HOUR() to find peak checkout hours during the day and schedule server scaling.

Syntax

Pass a single time or datetime expression to HOUR():

HOUR(time_or_datetime)
  • time_or_datetime: A TIME, DATETIME, TIMESTAMP, or valid string representation.

For TIME values like '-14:20:00' or '272:59:59', HOUR() returns the unsigned hour magnitude (14 and 272, up to 838).

Practical Example

Suppose your growth team inspects demo_orders to count how many orders arrive during each hour of the day.

SELECT
    HOUR(created_at) AS order_hour,
    COUNT(*) AS total_orders
FROM demo_orders
WHERE created_at >= '2026-05-12 00:00:00'
  AND created_at < '2026-05-13 00:00:00'
GROUP BY HOUR(created_at)
ORDER BY order_hour;
order_hour total_orders
9 3
14 8
21 5

Grouping by HOUR(created_at) lets you build a 24-hour activity histogram in a single query.

Common Mistakes & NULL Behavior

Watch out for these behaviors when calling HOUR():

  • TIME durations can exceed 23: Because MySQL TIME stores durations from -838:59:59 to 838:59:59, HOUR('48:15:00') returns 48, and HOUR('-12:30:00') returns 12 without a minus sign.
  • Bare DATE values return 0: Passing a date without a time part (HOUR('2026-05-12')) returns 0 (midnight) rather than NULL.
  • NULL or invalid strings return NULL: Passing NULL, '25:00:00' inside a DATETIME, or 'invalid' returns NULL.
  • No AM/PM conversion: HOUR() always returns 24-hour clock integers (0..23) for DATETIME values. Use DATE_FORMAT(col, '%h %p') if you need 12-hour labels.

Frequently Asked Questions

What does HOUR() return for a negative TIME value?

HOUR() drops the negative sign and returns the positive hour integer. For example, HOUR('-05:45:00') returns 5.

Can I use HOUR() on a TIMESTAMP column?

Yes. MySQL automatically converts the TIMESTAMP to your session time zone before extracting the hour.

Why did HOUR('2026-05-12') return 0?

MySQL interprets a DATE with no time portion as 00:00:00 (midnight), so the extracted hour is 0.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum