Skip to content
Advertisement

Postgres how to return values in between Min column and Max column

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement