Skip to content
Advertisement

SELECT after specific row with non-sequential (uuid) primary key

With the following table:

CREATE TABLE users (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    inserted_at timestamptz NOT NULL DEFAULT now()
    -- other fields
);

How could I retrieve n rows after a specific id, ordered by inserted_at ?

Advertisement

Answer

I want to retrieve n rows after a specific id, ordered by inserted_at.

I am expecting something like this:

select u.*
from users u
where u.inserted_at > (select u2.inserted_at from users u2 where u2.id = 'f4ae4105-1afb-4ba6-a2ad-4474c9bae483')
order by u.inserted_at
limit 10;

For this, you want one additional index on users(inserted_at).

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