Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query on a time range ignoring the date of timestamps

I'm trying to query a purchases table in my rails database (Postgres) and I want to query on time ranges.

For example, I'd like to know how many purchases were made between 2 PM and 3 PM across all dates.

There is a created_at column in this table but I don't see how to accomplish this without searching for a specific date as well.

I've tried:

Purchases.where("created_at BETWEEN ? and ?", Time.now - 1.hour, Time.now)

But this ultimately will just search for today's date with those times.

like image 273
user402516 Avatar asked Oct 14 '13 19:10

user402516


People also ask

How can I get data between two timestamps in SQL?

As stated above, the format of date and time in our table shall be yyyy:mm: dd hh:mm: ss which is implied by DATETIME2. The time is in a 24-hour format. Syntax: SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';

Can we compare date with timestamp in SQL?

Answer. The SQL99 (SQL3) Standard states that the DATE, TIME, and TIMESTAMP data types are not compatible for either assignment or comparison.

How can I get only date from timestamp?

You can use date(t_stamp) to get only the date part from a timestamp. Extracts the date part of the date or datetime expression expr.


1 Answers

You need to extract just the hour portion from created_at using PostgreSQL's date_part/extract function.

SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 20

For example, something like this:

Purchases.where(["EXTRACT(HOUR FROM created_at) BETWEEN ? AND ?", 13, 14])
like image 150
Philip Hallstrom Avatar answered Oct 05 '22 23:10

Philip Hallstrom