Home > Database > Mysql Tutorial > How to Find the Row Position of a Specific Entry in a MySQL `ORDER BY` Query?

How to Find the Row Position of a Specific Entry in a MySQL `ORDER BY` Query?

Susan Sarandon
Release: 2025-01-18 02:36:08
Original
799 people have browsed it

How to Find the Row Position of a Specific Entry in a MySQL `ORDER BY` Query?

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>
Copy after login

In this query:

  • We use a subquery to assign each row a position based on the sort order of the "name" column.
  • The @rownum variable is initialized to 0 and incremented for each row.
  • The outer query then filters the subquery results to find rows with the name "Beta".

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template