MacBook avec code sur un bureau

SQL – How to retrieve entries before and after an ID

It is possible, for example in the context of a competition, that we are looking to find out what are the 5 best scores preceding the one I just made. To do it in SQL, although a little tricky, it is not too complicated.

The 5 before me

SELECT *
FROM scores
WHERE score > (SELECT score FROM api_scores WHERE idscore = 34)
ORDER BY score
LIMIT 5

The 5 after me

SELECT *
FROM scores
WHERE score < (SELECT score FROM api_scores WHERE idscore = 34)
ORDER BY score DESC
LIMIT 5