fluent-kit icon indicating copy to clipboard operation
fluent-kit copied to clipboard

Sort randomly

Open EricWVGG opened this issue 6 years ago • 3 comments

This is a pretty common database method…

return SomeTable(on: req).sort(.random).all()
return SomeTable(on: req).sort(.random).range(..<50)

I am told that this currently does not exist as the MySQL and PostgreSQL syntaxes are not exactly the same. That said, I think the importance of this is pretty high.

PSQL: select * from your_table ORDER BY random() MySQL: select * from your_table ORDER BY rand()

EricWVGG avatar Jun 19 '19 18:06 EricWVGG

I agree, we should add this. First, we will need to add something like SQLRandom() to https://github.com/vapor/sql-kit that calls on the SQLDialect to get the correct function name.

tanner0101 avatar Jun 19 '19 19:06 tanner0101

Note that LIMIT/range() queries will still scan the entire table in this case, as a random number needs to be generated for every single row before sorting. That can have unexpected performance implications.

Efficiently fetching a random subset of rows from Postgres is not that easy: https://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql

MrMage avatar Jun 21 '19 07:06 MrMage

is this now implemented?

tkoehlerlg avatar Nov 08 '22 12:11 tkoehlerlg