New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for `order by random()` #1007

Closed
agersant opened this Issue Jul 8, 2017 · 3 comments

Comments

Projects
None yet
3 participants
@agersant

agersant commented Jul 8, 2017

Setup

Versions

  • Rust: 1.18
  • Diesel: 0.14.0
  • Database: SQLite
  • Operating System Windows

Feature Flags

  • diesel: sqlite
  • diesel_codegen: sqlite

Problem Description

There is no way to randomly sort the results of a select statement.

What are you trying to accomplish?

Returning a random subset of rows from a table. (ie. SELECT * FROM my_table LIMIT 20 ORDER BY RANDOM())

I know it's possible to work around this with my_table.order(sql::<types::Bool>("RANDOM()")).load(connection) but this seems like a useful feature to support in a safe manner.

Checklist

  • I have already looked over the issue tracker for similar issues.
@sgrif

This comment has been minimized.

Member

sgrif commented Jul 8, 2017

You can use sql_function! or no_arg_sql_function! for this. Generally we want to avoid exporting every possible function in SQL from Diesel, since it's trivial to declare the ones that you want.

@sgrif sgrif closed this Jul 8, 2017

@agersant

This comment has been minimized.

agersant commented Jul 8, 2017

Thanks!

@Thomasdezeeuw

This comment has been minimized.

Thomasdezeeuw commented Oct 1, 2017

It took me too long to figure this out so this is the code required:

no_arg_sql_function!(RANDOM, (), "Represents the sql RANDOM() function");

// Usage, using the post schema from the getting started guide.
let results = posts
    .order(RANDOM)
    .limit(5)
    .load::<Post>(&*connection)
    .expect("unable to load posts");

Which will generate the following query:

SELECT * ORDER BY RANDOM()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment