Skip to content
Advertisement

Finding the immediate upper and lower of X

For a project, I have a table nearest_values as

id value
1 8450
2 8500
3 8550
4 8600
5 8650
6 8700

Given a value say 8555, I need to select rows 2 and 3 ie immediately below and above as below.

id value
2 8500
3 8550

another example for say value 8601 the selected rows should be 4 & 5.

id value
4 8600
5 8650

Advertisement

Answer

Finding a single row above and below value x in a table using SQL. Tested using Postgres 13.

Alternately:

Result for 8555

id value
3 8550
4 8600

View on DB Fiddle

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