1

totally new in learning postgres/SQL I have a table called error_table that looks like this:

     id       min     max       error_percent

    10R46   1         25          9
    10R46   25        50          9
    100R91  50        100         4.5
    10R91   100       200         4.6
    10M95   200       300         5.5

but I am having a hard time generating a query on how to do this dynamically when my input number is 160, I would like to return the error_percent value 4.6 because 160 sits between the min column 100 and max column 200.

So far, here is what I am in my query

SELECT error_percent FROM error_table WHERE min <= 160 

Now the problem is, I cannot use max <=160. How will I able to dynamically query the corresponding max value of returned min result and use it as my max <= returned max?

IF you have a better solution than mine, I appreciate the share.

2
  • I don't understand your question, seems like a simple where min <= 160 and max > 160? What exactly do you mean with "and use it as my max <= returned max"? Commented Oct 9, 2020 at 7:11
  • Your data is inconsistent. Do you want two rows returned for 50? Or is the max not inclusive? Commented Oct 9, 2020 at 12:20

1 Answer 1

1

Use a range comparison:

SELECT error_percent
FROM error_table
WHERE min < 160 AND max >= 160;

This assumes that your ranges are open on the minimum side and closed on the maximum side. If not, then the above range comparison would need to be changed.

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

2 Comments

Alternatively, one could use where int4range(min, max, '[)') @> 160
Thanks for this suggestion mate, a build-in function for postgres

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.