I am working with a PostgreSQL database in a rails application and facing a challenge in extracting the user records on the basis of only the time component from timestamp type created_at column in my users table.
This query works fine:
users = User.where(" DATE_PART('hour', created_at) >= ?
AND DATE_PART('minute', created_at) >= ?
OR DATE_PART('hour', created_at) <= ?
AND DATE_PART('minute', created_at) <= ?",
10, 0, 15, 30).pluck :created_at
But I'm curious if there's a more elegant approach to extract the desired records. Essentially, I aim to query records based solely on time, excluding the date. For instance, I want to retrieve all users created between 10:00 and 12:30 on any day (year, month and day do not matter).
I also tried this:
User.where("EXTRACT(HOUR FROM created_at) BETWEEN ? AND ?", 14, 15)
but it's only dealing with hours not with the minutes.
Desired time could be 10-12 hours or 10:00-12:30.
How can I manage these minutes if I want to extract the records from 10:00 to 12:30?
In short, I'm seeking method where I can specify the desired time and obtain all records within those time slots.
PostgreSQL has a
timetype, that you can casttimestampto in order to extract everything from hours down (not excluding seconds and fractions of seconds), in one go. Demo at db<>fiddle:From RoR, you can pass the time fields into PostgreSQL
make_time(). The third field is adouble precision, which allows you to pass seconds with fractions:You can also pass any timestamp with a matching time, and cast to only use its
timeelement:It's possible to further speed this up by adding a functional index on
created_at: