SQL to return the rownum of a specific row? (using Oracle db)

jedierikb picture jedierikb · Feb 10, 2009 · Viewed 18.9k times · Source

In Oracle 10g, I have this SQL:

select dog.id as dogId from CANINES dog order by dog.codename asc

which returns:

id
--
204
203
206
923

I want to extend this query to determine the oracle rownum of a dog.id in this resultset.

I have tried

select rownum from 
(select dog.id as dogId from CANINES dog order by dog.codename asc) 
where dog.id=206

But this does not work out very well (it returns 1 no matter which dog.id I match on). I was expecting to get back 3.

Thanks for your help!


Notes

http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html

I am pretty sure I do not need to use rowid

Answer

Justin Cave picture Justin Cave · Feb 11, 2009

I suspect what you want is to use an analytic function (RANK, DENSE_RANK, or ROW_NUMBER), i.e.

SELECT rnk
  FROM (select dog.id as dogId,
               ROW_NUMBER() OVER( ORDER BY dog.codename ASC ) rnk
          from CANINES dog )
 WHERE dogId = 206

If the ID column in the CANINES table were not unique, RANK, DENSE_RANK, and ROW_NUMBER) would treat ties differently.

If you want to do this solely with ROWNUM,

SELECT rn
  FROM (
        SELECT dogId, rownum rn
          FROM (select dog.id as dogId
                  from CANINES dog 
                 order by dog.codename ASC) inner
       ) middle
 WHERE dogId = 206