#11900·dolt

Docs: how to sample random rows cheaply (ORDER BY RAND() scans the whole table)

Author: LaPingvinoCreated Sep 18, 2026Updated Sep 29, 2026
Labelsdocumentationenhancementsqlcustomer issue

Summary

This is mostly a documentation gap, with a possible performance win behind it.

Coming from MySQL, the first thing people write to look at a few random rows is ORDER BY RAND() LIMIT n. The docs list RAND() as supported but say nothing about sampling rows, TABLESAMPLE is neither supported nor mentioned, and I could not find any guidance on how to sample cheaply. Meanwhile ORDER BY RAND() has to scan the whole table and evaluate RAND() for every row (the sort itself appears to be a top-k already, judging by the timings below), so on large tables the obvious idiom is slow, and inside a subquery or join it can become unusable.

A primary-key probe is effectively free and is what people should be told to use.

Measurements

Database: lapingvino/kuwikt on DoltHub (public), table _templates with ~4.8M rows and primary key (page_id, seq). Dolt 2.3.5, local CLI (dolt sql -q), Linux x86_64.

sql
-- full scan: 3.4 s wall clock locally (of which ~0.75 s is CLI start-up); 16.7 s through the DoltHub API
select page_id, seq, name from _templates order by rand() limit 1;

-- key probe: 0.75 s locally (the same as `select count(*)`, i.e. start-up only); 0.9 s through the DoltHub API
select page_id, seq, name from _templates where page_id >= floor(rand() * 1358886) limit 1;

What I actually wrote first, and killed after five minutes, was a join on _page_text filtered by page_id IN (select page_id from _sections where heading = 'Dijmane' order by rand() limit 2) over a 3M-row table.

Suggestions

  1. Docs (the main ask). A short "sampling rows" note, for example next to the RAND() entry or on a performance page: recommend a primary-key range probe for "give me a random row", WHERE RAND() < p for approximate fractional samples, and warn that ORDER BY RAND() scans the whole table. I am happy to send a docs PR if you tell me where it should live.
  2. Possible performance win. Dolt's prolly trees could make sampling genuinely cheap: a rewrite of ORDER BY RAND() LIMIT n into random probes of the primary-key tree, or a TABLESAMPLE clause (which Postgres offers and Doltgres could expose), could pick uniformly random leaf chunks without touching the rest of the table.
  3. Longer term. Once sampling is cheap, a "random sample" affordance in the DoltHub table view and Dolt Workbench would fit Dolt's roots as a dataset tool; looking at a random slice is the most basic thing people do with a dataset. (If that part belongs in dolthub/dolthub-issues, feel free to split it off.)