Skip to content

Instantly share code, notes, and snippets.

@abedsujan
Created February 12, 2012 20:31
Show Gist options
  • Save abedsujan/1810735 to your computer and use it in GitHub Desktop.
Save abedsujan/1810735 to your computer and use it in GitHub Desktop.
MySQL::Select the Nth Highest Record in a Database Table
Step: MySQL provides LIMIT clause so we just have to leverage it to rewrite the query as follows
SELECT *
FROM table_name
ORDER BY column_name DESC
LIMIT n - 1, 1
Step :Query to get the nth highest record
SELECT *
FROM (
SELECT *
FROM table_name
ORDER BY column_name ASC
LIMIT n
) AS tbl
ORDER BY column_name DESC
LIMIT 1
Step: Using Sub-Query
SELECT *
FROM table_name AS a
WHERE n - 1 = (
SELECT COUNT(primary_key_column)
FROM products b
WHERE b.column_name > a. column_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment