Relix

Problem solving

A random, representative subset

Grain: one row per sampled row · Class: Sampling · Signals: a random sample, a representative subset, N at random, a preview, reproducible sample · Operators: SAMPLE … ROWS, SAMPLE p

The problem

"Give me 3 random events for a test fixture — the same 3 every time so the test is stable. Or roughly 40% of the rows as a quick preview. And let me sample within one region."

How to recognise it

The question asks for a random or representative subset, not a filtered or ranked one — a random sample, N at random, a representative subset, a preview, a spot check. The tell is that which rows come back is not determined by their values: any row is as eligible as any other. That rules out σ (which picks by a condition) and TOP (which picks by rank).

Two forms, and the tell is whether you want an exact count or a proportion:

SEED makes either one reproducible — the same seed and input always pick the same rows — which is what turns a random sample into a stable test fixture.

The data

Events := [
| id | region |
|----|--------|
| 1  | EMEA   |
| 2  | EMEA   |
| 3  | APAC   |
| 4  | EMEA   |
| 5  | APAC   |
| 6  | EMEA   |
| 7  | APAC   |
| 8  | EMEA   |
| 9  | APAC   |
| 10 | EMEA   |
];

Recipe 1: exactly N random rows (SAMPLE n ROWS)

SAMPLE n ROWS returns exactly n rows drawn uniformly. Pin the draw with SEED so a fixture or benchmark replays the same rows:

Query
query { SAMPLE 3 ROWS SEED 7 (Events) };
Result
 id  region
 ──  ──────
  4  EMEA
  2  EMEA
  3  APAC
(3 rows)

Ask for more than the relation holds and you get all of it, not an error:

Query
query { SAMPLE 50 ROWS SEED 7 (Events) };
Result
 id  region
 ──  ──────
  1  EMEA
  2  EMEA
  3  APAC
  4  EMEA
  5  APAC
  6  EMEA
  7  APAC
  8  EMEA
  9  APAC
 10  EMEA
(10 rows)

Recipe 2: a percentage (SAMPLE p)

SAMPLE p keeps each row with probability p — a streaming sample whose size varies. Use it for a rough preview of a large input where the exact count does not matter:

Query
query { SAMPLE 0.4 SEED 42 (Events) };
Result
 id  region
 ──  ──────
  3  APAC
  4  EMEA
  7  APAC
  8  EMEA
(4 rows)

Recipe 3: sample within a stratum

To sample within a subset — a stratum — filter first, then sample the result. The sample is drawn from just that subset:

Query
query { SAMPLE 2 ROWS SEED 1 (σ region = "APAC" (Events)) };
Result
 id  region
 ──  ──────
  7  APAC
  9  APAC
(2 rows)

For a sample of each stratum, run this per region (or union the per-region samples).

Variations

Pitfalls

Check it