EN
MySQL - find row number
5 points
In this article, we would like to show how to find row number in MySQL.
Quick solution:
xxxxxxxxxx
1
SET @row_number := 0;
2
3
SELECT w.`row_number`
4
FROM (
5
SELECT
6
(@row_number:=@row_number + 1) AS `row_number`,
7
t.*
8
FROM `table_name` t
9
) w
10
WHERE
11
w.column_name='column_value';
In the below example, we try to find row number where Simon Colins
is placed - row number depends on internal SELECT
query.
Example input:

Example query:
xxxxxxxxxx
1
SET @row_number := 0;
2
3
SELECT w.`row_number`
4
FROM (
5
SELECT
6
(@row_number:=@row_number + 1) AS `row_number`,
7
t.*
8
FROM `users` t
9
) w
10
WHERE
11
w.`name`='Simon' AND w.`surname`='Collins'
Example result:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(50) NOT NULL,
4
`surname` VARCHAR(50) NOT NULL,
5
PRIMARY KEY (`id`)
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
( `name`, `surname`)
3
VALUES
4
('John', 'Stewart'),
5
('Chris', 'Brown'),
6
('Kate', 'Lewis'),
7
('Ailisa', 'Gomez'),
8
('Gwendolyn', 'James'),
9
('Simon', 'Collins'),
10
('Taylor', 'Martin'),
11
('Andrew', 'Thompson');