intermediateselecting MySQL MariaDB SQL Server PostgreSQL SQLite
Select Random Rows
Return a random sample by ordering rows with the engine's random function and applying a row limit.
Created Last updated 5/5 supported engines validation-green1 example2 scenarios
Docker-validated Not currently validation-green
Example 1
Pick two random products
The random function produces a different sort key for each row. The limit then keeps two rows from that randomized order.
MySQL MariaDB
Engine-specific syntax
Source table data
Setup
CREATETABLE products (id INT, name VARCHAR(50));
INSERTINTO
products
VALUES
(1, 'Widget'),
(2, 'Gadget'),
(3, 'Doohickey'),
(4, 'Thing');
Validated query
SQL
SELECTCOUNT(*) AS sampled_rows
FROM
(
SELECT
id,
name
FROM
products
ORDERBYRAND ()
LIMIT2
) sample;
Expected result
sampled_rows
2
SQL Server
Engine-specific syntax
Source table data
Setup
CREATETABLE products (id INT, name VARCHAR(50));
INSERTINTO
products
VALUES
(1, 'Widget'),
(2, 'Gadget'),
(3, 'Doohickey'),
(4, 'Thing');
Validated query
SQL
SELECTCOUNT(*) AS sampled_rows
FROM
(
SELECTTOP2 id,
name
FROM
products
ORDERBY
NEWID ()
) sample;
Expected result
sampled_rows
2
PostgreSQL
Engine-specific syntax
Source table data
Setup
CREATETABLE products (id INT, name VARCHAR(50));
INSERTINTO
products
VALUES
(1, 'Widget'),
(2, 'Gadget'),
(3, 'Doohickey'),
(4, 'Thing');
Validated query
SQL
SELECTCOUNT(*) AS sampled_rows
FROM
(
SELECT
id,
name
FROM
products
ORDERBYRANDOM ()
LIMIT2
) sample;
Expected result
sampled_rows
2
SQLite
Engine-specific syntax
Source table data
Setup
CREATETABLE products (id INT, name TEXT);
INSERTINTO
products
VALUES
(1, 'Widget'),
(2, 'Gadget'),
(3, 'Doohickey'),
(4, 'Thing');
Validated query
SQL
SELECTCOUNT(*) AS sampled_rows
FROM
(
SELECT
id,
name
FROM
products
ORDERBYRANDOM ()
LIMIT2
) sample;
Expected result
sampled_rows
2
Result rows vary on each execution, so this command intentionally has no fixed expected rows.
Useful when
Where this command helps.
reviewing a random sample of records
showing random featured rows without a separate sampling table
Explanation
What the command is doing.
A simple random sample can be produced with ORDER BY on a random value, then limiting the result. MySQL, MariaDB, and SQL Server use different random functions than PostgreSQL and SQLite. This pattern is convenient for small tables, QA spot checks, and demos. For very large tables it can be expensive because the database must assign and sort a random value for many rows.