sqlpostgresqlrandomrow-numbergenerate-series

Joining a series in postgres with a select query


I'm looking for a way to join these two queries (or run these two together):

SELECT  s
FROM    generate_series(1, 50) s;

With this query:

SELECT id FROM foo ORDER BY RANDOM() LIMIT 50;

In a way where I get 50 rows like this:

series, ids_from_foo
1, 53
2, 34
3, 23

I've been at it for a couple days now and I can't figure it out. Any help would be great.


Solution

  • Use row_number()

    select row_number() over() as rn, a
    from (
        select a
        from foo
        order by random()
        limit 50
    ) s
    order by rn;