HOUR
HOUR is a built-in function in SQL that extracts the hour from a given time. It returns an integer value ranging from 0 to 23, corresponding to the hour in a 24-hour day.
HOUR(time)
- time: This parameter represents the exact time value from which the hour is to be extracted. It accepts a string formatted as a time (e.g., ‘15
Example
SELECT HOUR('15:30:00') AS 'Hour';
Output
+------+| Hour |+------+| 15 |+------+
Explanation
The HOUR function in MySQL is used to get the hour from a time. In the example, input time ‘15:30:00’ was passed to the HOUR function, and this returned 15, which is the hour in the provided time.
HOUR(timestamp): integer
- name: timestamp
Example
SELECT EXTRACT(HOUR FROM TIMESTAMP '2022-01-01 14:30:00');
Output
14
Explanation
The EXTRACT function in PostgreSQL is used to retrieve subfields such as year, month, day, hour, etc., from date/time columns. In the provided example, it extracts the hour from the timestamp ‘2022-01-01 14:30:00’, producing the number 14 as the result.
HOUR(expression)
- expression: This parameter is the time value from which SQL server will extract the hour. It can be a time, date, smalldatetime, datetime, datetime2, or datetimeoffset. The expression will return the hour as an integer.
Example
DECLARE @date DATETIME;SET @date = '01/01/2022 12:30:45';SELECT HOUR(@date) AS 'Hour';
Output
Hour----12
Explanation
In the code, a date-time variable @date
is declared and set to ‘01/01/2022 12:30:45’. The HOUR
function is then used to extract and return the hour portion of the time in the @date
variable. The output, 12
, shows the hour extracted from the @date
variable.
HOUR(date)
- date: Represents the input date value from which the hour needs to be extracted. This parameter has to be in DATE or TIMESTAMP format. The function will return the hour component of the input date as an integer in 24-hour format ranging from 0 to 23.
Example
SELECT EXTRACT(HOUR FROM TO_DATE('2021-09-22 17:30:00', 'YYYY-MM-DD HH24:MI:SS')) AS HOUR FROM dual;
Output
17
Explanation
The EXTRACT function is used to get a specific part from a datetime. In this case, HOUR is extracted from the given datetime value. The date string ‘2021-09-22 17:30:00’ is converted to a date first using TO_DATE(). This SQL will return the hour from the provided date-time which is 17 in this case.
HOUR(date)
- date: The parameter “date” is a string representing a date and time. The HOUR function extracts the hour from this date-time string as an integer ranging from 0 (representing 12
Example
SELECT strftime('%H', '2022-09-30 15:20:00') as 'Hour';
Output
Hour----15
Explanation
In the above code, the SQLite strftime('%H', '2022-09-30 15:20:00')
function is used to extract the hour from the datetime string. The ‘%H’ format specifier is used to get the hour in 24-hour format. The result is ‘15’, which indicates the 15th hour of the day or 3 PM.