Question: I am working on one site where I need to fetch records against dynamic value. My table structure is like this:

> 
> **Rule\_price Rul\_value**
> 
> 
> 
> ```
>   100       3  
>   200       5
>   250       6
> 
> ```
> 
> 

My question is that if I got value between 100 to 200 then it should fetch 100 (first record, the least value), if got value between 200 to 250 then it should fetch 200 and so on.

The value will match `Rule_price` value. If not clear ask me. Thanks.

Answer: 
The solution is to calculate the distance between the price and all prices, sort them and select smallest positive distance.

Like this:

```
SELECT rul_value, (rule_price - $price) as distance FROM  my_table WHERE (rule_price -  $price) < 0 ORDER BY distance DESC LIMIT 1

```

**NOTE**: This query uses `filesort`, which means it may be slow if you have lots of rows in this table.
The above answer (Yousaf) query fetch records but it fails on when value is equal to field value:like if finding value is 200 it fetch record of 100.For 200 it have to fetch 200 not 100.So i change the query little bit and works well.So in future may be help someone.

```
 SELECT rul_value, (rule_price - $price) as target 
FROM  my_table WHERE (rule_price -  $price) <= 0 ORDER BY target DESC limit 1 

```