MySQL: Get The Position Of The Record In The Table

August 09, 2012

Problem: there is a table in SQL database and we need to get a position of the row ordered by one of the fields, read more for the solution.

Solution: There is no SQL statement that will give you the position, but you can find how many records are above, and adding 1 to this will give you the position:

SELECT COUNT(*)
FROM tableName
WHERE fieldToOrderBy >
(
                SELECT fieldToOrderBy
                FROM tableName
                WHERE PK = 123
)