Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check input value between two columns

Tags:

sql

select

mysql

Below is my database schema.

id   from  to    value
1    1     10    5
2    11    NULL  10   -- I have stored 'NULL' for any value GREATER THAN 11

Now i have to select value where input like (4) is between from and to.

I know that it can be achieved with this query.

SELECT *
FROM   TABLE
WHERE  4 BETWEEN `from` AND `to`

But how to select value where input is like 15?

SELECT *
FROM   TABLE
WHERE  15 BETWEEN `from` AND `to`

In this case above query will not work because to column has null.

UPDATE

columen to will contain null if it can have any value.

Now If input value is 15, then query should return 2nd row, because 15 is not between 1 and 10 in 1st row and 15 is greater than 11 and to value can be anything greater than 11.

like image 247
Vijay Choudhary Avatar asked Apr 21 '26 10:04

Vijay Choudhary


1 Answers

SELECT *
FROM   TABLE
WHERE  15 BETWEEN coalesce(`from`,15) AND coalesce(`to`,15);
like image 195
Florin stands with Ukraine Avatar answered Apr 23 '26 00:04

Florin stands with Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!