SQL

Select Random N Rows from a Table

Learn how to retrieve a random subset of N records from any SQL table using ORDER BY RANDOM() or specific database functions for sampling data efficiently.

-- For PostgreSQL, MySQL, and SQLite
SELECT *
FROM your_table
ORDER BY RANDOM()
LIMIT 10;

-- Note: RANDOM() is for PostgreSQL/SQLite, RAND() is for MySQL.
-- For very large tables, this can be slow as it sorts the entire table.
-- Consider database-specific sampling methods for performance if available.
How it works: This SQL snippet demonstrates how to select a random sample of N rows from any given table. It uses `ORDER BY RANDOM()` (or `RAND()` in MySQL) to sort the rows randomly and then `LIMIT N` to retrieve the desired number of records. While convenient, be aware that sorting an entire table randomly can be inefficient on very large datasets. For optimal performance with large tables, consider using database-specific sampling functions if available.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs