SQL Random Row Generator

Generate SQL queries that select random rows — techniques for MySQL, PostgreSQL, SQLite, and SQL Server.

About Random Row Selection

Selecting random rows from a database table is a common requirement for sampling, A/B testing, randomized surveys, recommendation systems, and generating test data. However, the naive approach — ORDER BY RAND() — can be extremely slow on large tables because it requires generating a random number for every row in the table before sorting.

For large tables, better approaches include: selecting a random OFFSET (get the table count first, then SELECT with LIMIT 1 OFFSET random_number), using the random ID technique (WHERE id >= FLOOR(RAND() * MAX(id)) LIMIT N), or using database-specific functions like TABLESAMPLE in PostgreSQL. This tool generates efficient random selection queries for each major SQL database using the best method for your chosen dialect.

FAQ

Why is ORDER BY RAND() slow?
ORDER BY RAND() assigns a random value to every row in the table, then sorts all rows by that random value. For a table with 1 million rows, this generates and sorts 1 million random numbers — even if you only want 1 row. On large tables this can take seconds or minutes. The random OFFSET method avoids this by only generating one random number.
How do I get reproducible random results?
Use the seeded random option which generates SQL using RAND(seed) in MySQL or SETSEED() in PostgreSQL. With the same seed, you always get the same "random" rows — useful for reproducible testing, A/B test assignment, and consistent sampling across environments.