Skip to content
Advertisement

Find between which 2 numbers a value lies in MySQL

I have a variable @k=35.

and a table xrf having contents as show below.

+----+
| tt |
+----+
| 20 |
| 30 |
| 40 |
| 50 |
| 60 |
+----+

How to I get the values in between which @k exist in table xrf.

output is 30 and 40.

Advertisement

Answer

Using conditional aggregation

select 
  max(case when tt <= @k then tt end) lower, 
  min(case when tt > @k then tt end) upper
from mytable
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement