sqlcmd.net validated sql reference
intermediate selecting 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.

Docker-validated Not currently validation-green

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
Setup
CREATE TABLE products (id INT, name VARCHAR(50));

INSERT INTO
  products
VALUES
  (1, 'Widget'),
  (2, 'Gadget'),
  (3, 'Doohickey'),
  (4, 'Thing');
SQL
SELECT
  id,
  name
FROM
  products
ORDER BY
  RAND ()
LIMIT
  2;
SQL Server
Engine-specific syntax
Setup
CREATE TABLE products (id INT, name VARCHAR(50));

INSERT INTO
  products
VALUES
  (1, 'Widget'),
  (2, 'Gadget'),
  (3, 'Doohickey'),
  (4, 'Thing');
SQL
SELECT
  TOP 2 id,
  name
FROM
  products
ORDER BY
  NEWID ();
PostgreSQL
Engine-specific syntax
Setup
CREATE TABLE products (id INT, name VARCHAR(50));

INSERT INTO
  products
VALUES
  (1, 'Widget'),
  (2, 'Gadget'),
  (3, 'Doohickey'),
  (4, 'Thing');
SQL
SELECT
  id,
  name
FROM
  products
ORDER BY
  RANDOM ()
LIMIT
  2;
SQLite
Engine-specific syntax
Setup
CREATE TABLE products (id INT, name TEXT);

INSERT INTO
  products
VALUES
  (1, 'Widget'),
  (2, 'Gadget'),
  (3, 'Doohickey'),
  (4, 'Thing');
SQL
SELECT
  id,
  name
FROM
  products
ORDER BY
  RANDOM ()
LIMIT
  2;

Result rows vary on each execution, so this command intentionally has no fixed expected rows.

Where this command helps.

  • reviewing a random sample of records
  • showing random featured rows without a separate sampling table

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.