Performing Hours of Operation Query in PostgreSQL
In PostgreSQL, you can perform a query to find all records that are "open" based on specified hours of operation using a combination of date and time comparisons. However, this approach can become complex, especially if the hours wrap around the end of the week.
Proposed Solution Using tsrange Type
To simplify and optimize this query, you can redesign the table to store opening hours as a set of tsrange (range of timestamp without time zone) values. This requires PostgreSQL version 9.2 or later and involves the following steps:
Table Layout:
Example Data:
CREATE TABLE hoo ( hoo_id serial PRIMARY KEY , shop_id int NOT NULL , hours tsrange NOT NULL );
INSERT INTO hoo(shop_id, hours) VALUES (123, '[1996-01-03 18:30, 1996-01-04 05:00]');
Exclusion Constraint:
Helper Functions:
Optimized Query:
Using the new table structure and helper functions, you can simplify your query to:
SELECT * FROM hoo WHERE hours @> f_hoo_time(now());
Benefits:
The above is the detailed content of How Can PostgreSQL's `tsrange` Type Optimize Queries for Business Hours?. For more information, please follow other related articles on the PHP Chinese website!