SQL HOUR function
Returns the hour of day as an integer, the standard key for hourly traffic and shift-based grouping.
- Returns
integer- In this category
- 40 of 121
語法
EXTRACT(hour FROM ts)
DATEPART(hour, ts) -- SQL Server
HOUR(ts) -- MySQL
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Different name or syntax | DATEPART(hour, ts); no HOUR() shorthand |
| PostgreSQL | Different name or syntax | EXTRACT(hour FROM ts) |
| MySQL | 是 | Supported under this name. |
| SQLite | Different name or syntax | strftime('%H', ts) returns text |
| Oracle | Different name or syntax | EXTRACT(hour FROM ts) needs a TIMESTAMP, not a DATE |
範例
PostgreSQL
SELECT EXTRACT(hour FROM created_at) AS hr, COUNT(*) FROM orders GROUP BY 1 ORDER BY 1;
SQL Server
SELECT DATEPART(hour, created_at) AS hr FROM orders;
SQLite
SELECT CAST(strftime('%H', created_at) AS INTEGER) AS hr FROM orders;
小知識
- Oracle's EXTRACT(hour) raises ORA-30076 on a plain DATE: CAST it to TIMESTAMP first, or use TO_CHAR(d, 'HH24').
- SQLite's strftime('%H') returns zero-padded text; CAST to INTEGER before numeric comparisons.
- PostgreSQL has no HOUR() shorthand: EXTRACT(hour FROM ts) or DATE_PART('hour', ts) are the spellings.
Questions about HOUR
Why does EXTRACT(hour) fail on Oracle DATE columns?
EXTRACT reads datetime fields from TIMESTAMP values; a DATE needs TO_CHAR(d, 'HH24') or an explicit CAST to TIMESTAMP first.
Is the hour 0-based?
Yes, 0 through 23 on every engine. SQLite's %H is also zero-padded, which keeps text sorting correct.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.