Search code examples
ruby-on-railsoracle-databaseactiverecordrownum

Row position in 100k+ records


i have this code to get the position of each record:

Message.all.each_with_index do |msg, i|
    message_order[msg.id] = i
end

But now i have 100k+ messages and it takes to long to iterate over all the records. Can anyone tell me how to do this more performant? (I'm using oracle)

I thought about rownum but didn't come to a solution. A solution which returns the position for just one message would be great.


Solution

  • I don't know if I have understood your problem.

    If you need the message with a specified order id (for example: 5), you can execute something like:

    SELECT message
    FROM (SELECT message, ROWNUM AS ID
          FROM (SELECT message
                FROM tab1
                ORDER BY some_date))
    WHERE ID = 5;
    

    Or, using analytical functions:

    SELECT message
    FROM (SELECT message,
                 ROW_NUMBER() OVER(ORDER BY some_date) AS ID
          FROM tab1)
    WHERE ID = 5;