Today I Learned

hashrocket A Hashrocket project

Randomly Sort Rows in Postgres

I'm on a bit of a random kick lately. Today I learned you can randomly sort rows returned in a query using Postgres' random() function.

SELECT *
FROM users
ORDER BY random()

What it does is it calculates a random value for each row returned, and then orders by that calculated value. If the query returns a lot of rows this can be slow, so probably more useful for exploration or one-offs not necessarily for production uses.

See More #sql TILs
Looking for help? Hashrocket developers believe that data quality is as important as code quality. We enjoy all the challenges of relational databases, from finding the fastest index, to structuring data to fit the needs of an application. We're eager to share our experiences; check out PG Casts, our series of free PostgreSQL screencasts.