Home > Software design >  SQL to replace multiple "BETWEEN ... AND"
SQL to replace multiple "BETWEEN ... AND"

Time:05-06

Suppose I have a small lookup table like this:

ULimit LLimit
1 4
11 14
21 24

I want to write an SQL to test if a particular value falls in any one of the ranges specified in that table....

Although equivalently I could do away with that lookup table and write something like below instead:

SELECT Field1 FROM tableA
WHERE (Field1 BETWEEN 1 AND 4) OR (Field1 BETWEEN 11 AND 14) OR (Field1 BETWEEN 21 AND 24) OR ...

But it is not viable in my case because the number of ranges to be tested can vary from time to time, hence this question.

Is it possible? Please advise.

CodePudding user response:

SELECT Field1
FROM tableA
INNER JOIN tableLimits
    ON tableA.Field1 BETWEEN tableLimits.ULimit AND tableLimits.LLimit
  •  Tags:  
  • sql
  • Related