Question

I have what seems like a very silly question to me. I have a query that looks something like:

SELECT id FROM myTable WHERE valueCol BETWEEN :x and :y;

This works great when :x <= :y BUT, when :x > :y it doesn't return the rows I want! For this case I have to manually reverse the variables to get it to work correctly.

Is there a way to write a between clause where the order of the variables doesn't matter?

PS> I included SQL since I am pretty sure this is just a general sql issue.

Was it helpful?

Solution

Yes that's easy:

SELECT id 
FROM myTable 
WHERE valueCol BETWEEN LEAST(:x,:y) and GREATEST(:x,:y);

OTHER TIPS

You could do the check yourself and swap the values, or, you could do something like this and let Oracle figure it out:

BETWEEN LEAST(:x,:y) AND GREATEST(:x,:y)

you can use a case:

between case when :x <= :y then :x else :y end 
and case when :x <= :y then :y else :x end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top