SQL
Select Random Records for Featured Content
Discover how to retrieve a specified number of random records from a SQL table, perfect for displaying featured products, testimonials, or random articles.
-- PostgreSQL
SELECT * FROM Products
ORDER BY RANDOM()
LIMIT 5;
-- MySQL
-- SELECT * FROM Products
-- ORDER BY RAND()
-- LIMIT 5;
-- SQL Server
-- SELECT TOP 5 * FROM Products
-- ORDER BY NEWID();
How it works: This snippet provides a way to select a random subset of records from a database table. It's commonly used for displaying featured content like products, blog posts, or user testimonials on a website. The ORDER BY RANDOM() (PostgreSQL) or ORDER BY RAND() (MySQL) clause shuffles the rows randomly, and LIMIT (or TOP for SQL Server) then picks a specified number of those shuffled records.