Ny way to get the position of a value in a table returned by a SELECT statement

sqlite

I have the following statement:

SELECT id FROM myTable WHERE aCondition == 1 ORDER BY id

which returns a table like this one for example:

id
1
3
4
5

But what I need is to know the position of a given number. For example 4 has position 2 in the database.

I can do that with normal C code of course but I wonder if I can do everything in SQL, something like this for example:

SELECT ROWNUMBER(id, 4) FROM myTable WHERE aCondition == 1 ORDER BY id

which should return:

ROWNUMBER
2

Best Answer

There is a ROW_NUMBER() analytic function but I don't think it's available in SQLite. So, here's a generic approach (which may be quite slow):

SELECT pos - 1 AS ROWNUMBER     --- the "-1" is to get the C-style row numbering
FROM
  ( SELECT b.id
         , COUNT(*) AS pos 
    FROM myTable AS a
      JOIN myTable AS b
        ON a.id <= b.id 
    WHERE a.aCondition = 1
      AND b.aCondition = 1
      AND a.id <= 4             --- optional for  
      AND b.id <= 4             --- performace 
    GROUP BY b.id
  ) AS tmp
WHERE id = 4

Note that you should not use the additional two lines (checks), if your final WHERE checks for something else than id.


Rethinking, there's an even better way, because you only want the Row_Number of the last element in that list. There is no need to number them all, we can just count them:

SELECT CASE WHEN maxid = 4     --- so we don't get a RowNumber for an @id
              THEN cnt-1       --- that does not meet the condition
              ELSE NULL        --- or is not in the table at all 
       END AS ROWNUMBER    
FROM
  ( SELECT MAX(id)  AS maxid
         , COUNT(*) AS cnt 
    FROM myTable AS a
    WHERE a.aCondition = 1
      AND a.id <= 4   
  ) AS tmp