MySQL get row position in ORDER BY

Use this:

SELECT x.id, 
       x.position,
       x.name
  FROM (SELECT t.id,
               t.name,
               @rownum := @rownum + 1 AS position
          FROM TABLE t
          JOIN (SELECT @rownum := 0) r
      ORDER BY t.name) x
 WHERE x.name="Beta"

…to get a unique position value. This:

SELECT t.id,
       (SELECT COUNT(*)
          FROM TABLE x
         WHERE x.name <= t.name) AS position,
       t.name    
  FROM TABLE t      
 WHERE t.name="Beta"

…will give ties the same value. IE: If there are two values at second place, they’ll both have a position of 2 when the first query will give a position of 2 to one of them, and 3 to the other…

Leave a Comment