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.

SqlData Integrity

Code

snippet
-- 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

FAQ

What are the relations in play here?
`generate_series`.