1

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?

  • Another table design?
  • Put Integer.MIN and Integer.MAX for the null values?
  • Maybe there is a query that can be used that can handle these null
    values?
3
  • Please add the expected result to your question. It seems that you would need to enhance your WHERE condition with IS NULL OR boolean constructs. Commented Jul 12, 2022 at 15:44
  • You could give your min and max an upper and lower bound like WHERE COALESCE(min, -9999999) <= some_value AND some_value <= COALESCE(max, 9999999) (as an option) Commented Jul 12, 2022 at 15:44
  • That was something in the lines of what I thought, but by just replacing the null upper and lower bound in the records themselves instead of using COALESCE function. Commented Jul 12, 2022 at 15:48

2 Answers 2

3

Use ranges:

WHERE int4range(min, max, '[]') @> some_value

A GiST index can make this query fast.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

You mean '[]' as third argument, right?
@LaurenzAlbe You are right. Sorry for my mistake.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.