In SQL, this is a common issue to query the previous and next entries of the database. In order to achieve this, we are going to use a table that is sorted by the `id` field. To get the previous, the technique consists in sorting all the fields that are lower that the current one and taking the first one.

SELECT *
FROM `table`
WHERE `id` < $current_id
ORDER BY `id` DESC
LIMIT 1

Let's take an example with the values [8, 3, 4, 9, 6, 1]. We want to get the previous of 8.

  • WHERE `id` < $current_id
    We first take all the values strictly lower than 8
    Result: [3, 4, 1, 6]
  • ORDER BY `id` DESC
    We then sort them in descending order
    Result: [6, 4, 3, 1]
  • LIMIT 1
    We take the first one
    Result: 6

You can apply the same method for the next entry:

SELECT *
FROM `table`
WHERE `id` > $current_id
ORDER BY `id` ASC
LIMIT 1

Random Posts

  • Project – MMO-Champion Optimization (0 Comments) -- August 4, 2009

    MMO-Champion is the biggest news website of World of Warcraft. The main page is viewed millions times a month and was done with old school tables. As a result, it was really slow to load but worse, all the content had to be loaded before being displayed. The first thing I did was to rewrite t...

  • Dangerous Bracket Notation for Strings (0 Comments) -- August 13, 2009

    The bracket notation for string is incomplete in Javascript and does not work in IE7. This is really painful to migrate to the .charAt(pos) equivalent, this is why i recommend you not to use it. // Bracket Notation "Hello World!" // > "W" // Real Implementation "Hello World!".charAt(6) /...

  • Project – SC2Mapster (0 Comments) -- March 22, 2010

    Starcraft II has been a beta for a month and I've been actively working on the map making features. The Galaxy Map Editor has not been released yet however it is already possible to do edit the map files. My goal is not to develop a map but to build a community around that editor. With Curse ...

  • SmallHash – Information Compression (0 Comments) -- August 7, 2009

    SmallHash encodes any range of integers into the smallest possible string. This way, you can use the hash part of your url with efficiency....

  • Javascript – Type Casting (0 Comments) -- September 4, 2009

    Comparison In Javascript there are 3 types we are often comparing: String, Number and Boolean. After digging through the ECMA-262 specifications, here is the behaviour of the == operator (11.9.3) on these types: Number == String Typecasted as follow: Number == Number(String) Number == Boolean ...

Trackback

No comments until now

Add your comment now