SetSeed Reproducible Random Data
Seed random() with setseed to replay the exact same sequence in a session, which makes generated fixtures and sampled comparisons reproducible.
Code
-- setseed() 固定 random() 的序列起点:同一种子在同一会话里,
-- 后续 random() 每次重放完全一致——测试夹具与抽样对比的可复现基线
SELECT setseed(0.42);
SELECT g, round(random() * 100) AS dice
FROM generate_series(1, 5) g;
-- 重新播种:同一个 0.42 又会得到同一批数
SELECT setseed(0.42);
SELECT g, round(random() * 100) AS dice_again
FROM generate_series(1, 5) g;
-- 实战:可复现的布尔标记列;种子是会话级状态,
-- 想让整批数据稳定,先播种再一次性生成
SELECT setseed(0.07);
SELECT id, (random() < 0.5) AS flag
FROM generate_series(1, 10) AS id
ORDER BY id;What the code does
Several statements share this file — SELECT, with generate_series among the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order.
Using it
Run the statement against the generate_series table.
Key statements
SELECT id, (random() < 0.5) AS flag
FROM generate_series(1, 10) AS id
ORDER BY id;
SELECT g, round(random() * 100) AS dice_again
FROM generate_series(1, 5) g;
SELECT g, round(random() * 100) AS dice
FROM generate_series(1, 5) g;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What are the relations in play here?
- `generate_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.