Skip to content
Advertisement

Extremely slow “row_number() over order” query

I have a users table with columns (id, xp, …) and around 1.5 million rows.

I am getting someone’s position in the XP leaderboard with the following query (which took 33 seconds to execute):

My table definition:

But it is extremely slow. Although it is not surprising considering it sorts the whole table and filter it, I don’t know how I could improve/optimize this query.

I did SET work_mem TO '1 GB';. It helped a bit but not much.

Any help would be appreciated. Thanks in advance.

Advertisement

Answer

You can write the query like this:

This can take advantage of an index on users(id, xp). This should totally eliminate any sorting. An index on users(xp) could also be helpful if the rows are quite wide and Postgres can use an index-only scan.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement