Question

I have this table:

Id   Name
1    M
2    P
3    A1
4    C
5    A2
6    T
1009 A2
1011 A1
1010 A3

I can get it sorted by Id if Id < 1000 and by Name if Id > 1000 (thanks to the help of people here) with this query:

SELECT *
FROM table1
ORDER BY
  CASE WHEN Id < 1000 THEN Id ELSE 1000 END,
  Name;

Which gives

Id   Name
1    M
2    P
3    A1
4    C
5    A2
6    T
1009 A2
1010 A3
1011 A1

Now, given an Id, I want the next row in the order I just ordered by. So far, I've managed to get the result with two SQL queries, based on the givenId. If givenId < 1000 I do:

SELECT *
FROM table1
WHERE
  Id > @givenId
ORDER BY
    CASE WHEN Id < 1000 THEN Id ELSE 1000 END,
    Name
LIMIT 1

If givenId > 1000 I do:

SELECT *
FROM table1
WHERE
  Id > 1000 AND Name > (SELECT Name FROM table1 WHERE Id = @givenId)
ORDER BY
    CASE WHEN Id < 1000 THEN Id ELSE 1000 END,
    Name
LIMIT 1

The Id with value 1000 will never exist so I don't have to worry about that case. This works, but I'm wondering if there's a better way to do this? Perhaps with one query instead of two? I've tried to come up with something better but can't seem to.

No correct solution

OTHER TIPS

This should get you started:

SELECT *
FROM (
  SELECT Id, Name, LEAD(Id) OVER w AS Next_Id, LEAD(Name) OVER w AS Next_Name
  FROM table1
  WINDOW w AS (ORDER BY CASE WHEN Id < 1000 THEN Id ELSE 1000 END, Name)
) WHERE Id = 6;

Note that the order by is working correctly as it returns Id = 1011 as the next Id.

https://dbfiddle.uk/?rdbms=sqlite_3.27&fiddle=ce891ef6631a142500b59ff2c686e108

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top