How to add a column from a select query but the value from the new column will be the row count of the MySQL select query?


For this, you can use MySQL row_number(). Let us first create a table −

mysql> create table DemoTable1342
   -> (
   -> Score int
   -> );
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1342 values(80);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1342 values(98);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1342 values(78);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1342 values(89);
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1342;

This will produce the following output −

+-------+
| Score |
+-------+
|    80 |
|    98 |
|    78 |
|    89 |
+-------+
4 rows in set (0.00 sec)

Following is the query to add a column from a select query but the value from the new column will be the row count of the MySQL select query −


mysql> select Score,row_number() over() as `Rank` from DemoTable1342 order by Score DESC;

This will produce the following output −

+-------+------+
| Score | Rank |
+-------+------+
|    98 |    1 |
|    89 |    2 |
|    80 |    3 |
|    78 |    4 |
+-------+------+
4 rows in set (0.32 sec)

Updated on: 05-Nov-2019

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements