Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add ROW INDEX as a column to SQL SELECT query?

Tags:

Assume I've SQL query like this:

SELECT id, name, index(not a real column) FROM users ORDER BY rating DESC

I want to add column to selected columns that will represent the index of the record.

Example:

 id    name  rating
 1     a     4
 2     b     2
 3     c     8
 4     d     5

For this table I want to get:

 id    name  rating  index
 3     c     8       1
 4     d     5       2
 1     a     4       3
 2     b     2       4
like image 592
Yarin Gold Avatar asked Nov 25 '12 11:11

Yarin Gold


People also ask

How do you create an index in a select statement?

SQL Server CREATE INDEX statement In this syntax: First, specify the name of the index after the CREATE NONCLUSTERED INDEX clause. Note that the NONCLUSTERED keyword is optional. Second, specify the table name on which you want to create the index and a list of columns of that table as the index key columns.

How do I select a column for an index in SQL Server?

An important point to consider after selecting the proper columns to be involved in the index key is the order of the columns in the index key, especially when the key consists of multiple columns. Try to place the columns that are used in the query conditions first in the SQL Server index key.


1 Answers

Try the following to get the row_index:

set @row_num = 0; 
SELECT id,name,rating, @row_num := @row_num + 1 as row_index FROM users
ORDER BY rating desc;
like image 158
bonCodigo Avatar answered Oct 07 '22 20:10

bonCodigo