SQL

Select Random N Records from a SQL Table

Discover efficient ways to fetch a specified number of random records from your SQL database, a common requirement for features like "related items" or data sampling.

-- PostgreSQL / SQLite 
SELECT * 
FROM your_table 
ORDER BY RANDOM() 
LIMIT 5; 

-- MySQL 
-- SELECT * 
-- FROM your_table 
-- ORDER BY RAND() 
-- LIMIT 5; 

-- SQL Server 
-- SELECT TOP 5 * 
-- FROM your_table 
-- ORDER BY NEWID();
How it works: This query retrieves a specified number of random records from a table. It orders the entire table randomly using database-specific functions ('RANDOM()' for PostgreSQL/SQLite, 'RAND()' for MySQL, 'NEWID()' for SQL Server) and then limits the result set to the desired number of records. This is ideal for showing shuffled content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs