Find row position in MySQL ORDER BY
query
When sorting a MySQL table in ascending order by a specific column, determining the location of a specific row can be a useful task. Here is the solution on how to retrieve a single row and its position among other sorted rows:
Using MySQL’s built-in variables and subqueries, the following query can accomplish this task:
<code class="language-sql">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'</code>
In this query:
The result is a single row containing its corresponding position in the sort order.
The above is the detailed content of How to Find the Row Position of a Specific Entry in a MySQL `ORDER BY` Query?. For more information, please follow other related articles on the PHP Chinese website!