Reputation: 252
Let's say I have a table with following columns.
id | min | max |
---|---|---|
1 | null | -101 |
2 | -100 | 100 |
3 | 101 | 200 |
... | ||
99 | 1000 | null |
I want to be able to find the record based on a value parameter where min <= value and value >= max.
SELECT *
FROM my_table t
WHERE min <= some_value and some_value <= max
The problem is that the lowest and the highest record have no upper or lower bound.
My question is what is the best practice for these cases?
Upvotes: 1
Views: 368
Reputation: 12484
You can use the range types and range functions built into PostgreSQL to handle this:
SELECT *
FROM my_table t
WHERE int8range(min, max, '[]') @> somevalue;
The '[]'
argument makes the min and max values inclusive, and a null for either min or max makes the range unbounded on that side.
Upvotes: 3
Reputation: 246698
Use ranges:
WHERE int4range(min, max, '[]') @> some_value
A GiST index can make this query fast.
Upvotes: 3