Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to MySQL Between used for Higher value to Lower value?

Tags:

sql

mysql

between

Here I mentioned query:

lowerValue = 3, upperValue = 6

SELECT * FROM SampleTable where tableDay BETWEEN 'lowerValue' AND 'upperValue';

This query is working fine, but I need given below query type

lowerValue = 3, upperValue = 6

SELECT * FROM SampleTable where tableDay BETWEEN 'upperValue' AND 'lowerValue';

It's return as empty list, because both values are dynamic, what I'm doing wrong?

like image 727
Udayakumar Avatar asked Oct 24 '25 15:10

Udayakumar


2 Answers

As a quickfix you could go with GREATEST() / LEAST() comparison functions:

SELECT *
FROM   SampleTable
WHERE  tableDay BETWEEN LEAST(upperValue, lowerValue) AND
                        GREATEST(upperValue, lowerValue);

but if upperValue can be lesser than lowerValue then use different names.

like image 142
manlio Avatar answered Oct 26 '25 06:10

manlio


Your first argument must always be the lower one.

From documentation of SQL:

test_expression [ NOT ] BETWEEN begin_expression AND end_expression

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

like image 20
Tikkes Avatar answered Oct 26 '25 06:10

Tikkes



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!