Home > Database > Mysql Tutorial > How to Add Row Numbers to Sorted SELECT Results in MySQL?

How to Add Row Numbers to Sorted SELECT Results in MySQL?

Mary-Kate Olsen
Release: 2025-01-22 00:08:11
Original
409 people have browsed it

How to Add Row Numbers to Sorted SELECT Results in MySQL?

MySQL: Retrieve row number from sorted SELECT results

Question:

How to get the row number of the sorted item in the SELECT statement of MySQL?

Background:

Consider a table called 'orders' containing columns 'orderID' and 'itemID'. The query shown below calculates the order quantity by 'itemID':

<code class="language-sql">SELECT itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;</code>
Copy after login

This query returns the item count but not the row number.

Solution:

To retrieve the line number, use the following technique:

  1. Initialize a variable to store the current line number:
<code class="language-sql">SET @rank=0;</code>
Copy after login
  1. Modify the original query to use variables to assign row numbers:
<code class="language-sql">SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;</code>
Copy after login
  1. Execute another SELECT statement to retrieve the final row count:
<code class="language-sql">SELECT @rank;</code>
Copy after login

Example:

The following query returns the row number and item count:

<code class="language-sql">SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC;
SELECT @rank;</code>
Copy after login

Output:

<code>1 | 388 | 3
2 | 234 | 2
3 | 693 | 1
4 | 3432 | 1
5 | 3459 | 1</code>
Copy after login

Final row count is 5.

The above is the detailed content of How to Add Row Numbers to Sorted SELECT Results in MySQL?. 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