Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting row number for query

I have a query which will return one row. Is there any way I can find the row index of the row I'm querying when the table is sorted?

I've tried rowid but got #582 when I was expecting row #7.

Eg:

    CategoryID  Name            
    I9GDS720K4  CatA
    LPQTOR25XR  CatB
    EOQ215FT5_  CatC
    K2OCS31WTM  CatD
    JV5FIYY4XC  CatE
--> C_L7761O2U  CatF <-- I want this row (#5)
    OU3XC6T19K  CatG
    L9YKCYAYMG  CatH
    XKWMQ7HREG  CatI

I've tried rowid with unexpected results:

SELECT rowid FROM Categories WHERE CategoryID = 'C_L7761O2U ORDER BY Name

EDIT: I've also tried J Cooper's suggestion (below), but the row numbers just aren't right.

 using (var cmd = conn.CreateCommand()) {
        cmd.CommandText = string.Format(@"SELECT (SELECT COUNT(*) FROM Recipes AS t2             WHERE t2.RecipeID <= t1.RecipeID) AS row_Num 
                FROM Recipes AS t1 
                WHERE RecipeID = 'FB3XSAXRWD'
                ORDER BY Name";
        cmd.Parameters.AddWithValue("@recipeId", id);
        idx = Convert.ToInt32(cmd.ExecuteScalar());
like image 684
Echilon Avatar asked Feb 05 '12 18:02

Echilon


People also ask

How do you find the row number?

In the cell, type the formula = ROW() and press enter. The ROW function returns the row number 7 as given in the argument. Similarly, if you try writing = ROW(M9), the formula returns the row number 9 as the row number is already given in the argument. It's as easy as that.

What is ROW_NUMBER () in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.


1 Answers

Here is a way to get the row number in Sqlite:

SELECT CategoryID,
       Name,
       (SELECT COUNT(*)
        FROM mytable AS t2
        WHERE t2.Name <= t1.Name) AS row_Num
FROM mytable AS t1
ORDER BY Name, CategoryID;
like image 200
J Cooper Avatar answered Oct 21 '22 18:10

J Cooper