← Back to SQL, page 14

sql-0264 · Medium mid

Return a random sample of 3 rows from a table. What are the trade-offs of ORDER BY random()?

ORDER BY random() LIMIT 3 is simple and correct but sorts the whole table, which is slow on large data. Faster options include picking random ids within the id range (biased if ids have gaps), filtering with WHERE random() % 100 = 0 for an approximate share, or PostgreSQL's TABLESAMPLE.

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT COUNT(*) AS sampled FROM (SELECT id FROM employees ORDER BY random() LIMIT 3);
sampled
3

The output changes on every run, so only the row count is shown here, which stays the same. Sorting by a random key gives every row an equal chance but needs a full scan and sort.

For a rough 1-in-N sample without sorting, filter instead. The share is approximate:

text
SELECT * FROM big_table WHERE abs(random()) % 100 = 0;   -- about 1 percent

PostgreSQL offers TABLESAMPLE SYSTEM (1) (page-level, fast, clustered) and TABLESAMPLE BERNOULLI (1) (row-level, slower, more even), and setseed() or REPEATABLE (seed) for reproducible samples (not run here).

For tests that must be reproducible, sample by a hash of the id rather than a random function.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT COUNT(*) AS sampled FROM (SELECT id FROM employees ORDER BY random() LIMIT 3);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ORDER BY random() LIMIT n is simple but sorts everything
  • Random filters give approximate fractions cheaply
  • PostgreSQL TABLESAMPLE samples pages or rows
  • Hash-based sampling is reproducible

Common mistakes

  • Using ORDER BY random() on very large tables
  • Picking random ids when ids have big gaps

Follow-ups

  • How would you sample 1 percent of users per country?
  • How would you make a sample reproducible?

Tips

  • Mention the sort cost