Search code examples
sqlsqliteextractrows

Extracting rows from SQL query given a certain value


The column c is in ascending order as you can see below.

Let's say I have a value x = 25; I want to extract the rows between which 25 lies corresponding to the c column. Clearly 25 lies between rows 2 and 3.

How can I extract rows 2 and 3 from a SQL query?

a b c
100 200 5
700 2000 20
600 110 100

Solution

  • Find all the values less or equal to 25. Then order them by c and take the first.

    Do it again for c greater than 25.

    You can do two queries and union them.

    select *
    from table
    where c <= 25
    order by c desc
    limit 1
    
    union
    
    select *
    from table
    where c > 25
    order by c asc
    limit 1