Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sqlite checking if value in one row is between values in next rows without loop

Let’s say that I have sql table like this:

id |  val_1 | val_2 | 
1  |  50    |  130  | -
2  |  70    |  110  | False
3  |  60    |  135  | True
4  |  40    |  70   | True

...

Now, I want to check if (val_1 50 is between 70 AND 110) OR ( val_2 130 is between 70 and 110), which gives False, and the next row which gives True coz 130 is between 60 and 135 and so on. Is that possible with window functions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the lag function to get the previous row:

SELECT id, val_1, val_2,
       LAG(val_1) OVER (ORDER BY id ASC) BETWEEN val_1 AND val_2 OR
       LAG(val_2) OVER (ORDER BY id ASC) BETWEEN val_1 AND val_2
FROM   mytable
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading