jeudi 25 février 2021

SQLite recalculates random() multiple times in subquery or CTE

If I run the following query:

WITH cte AS(SELECT random() AS rand)
SELECT rand,rand FROM cte;

the value rand is calculated once, and the same value appears twice in in the result.

If I run that with a table:

DROP TABLE IF EXISTS data;
CREATE TABLE data(n int);
INSERT INTO data(n) VALUES(1),(2),(3),(4),(5);
WITH cte AS(SELECT random() AS rand FROM data)
SELECT rand,rand FROM cte;

… the value for rand is recalculated for every instance, and so each row in the result set has two different values. See http://sqlfiddle.com/#!5/73fd4/1

I expected random() to be recalculated for each row, but I didn’t expect expect that the rand value be recalculated after the CTE.

I don’t think this is standard behaviour, and it certainly isn’t how PostgreSQL, SQL Server and MySQL work.

How do I get SQLite to calculate the rand value only once per iteration?




Aucun commentaire:

Enregistrer un commentaire