1

I have a query like this

select * from (select generate_series(1, 1030) as id) t where id=floor(random() * 1030 + 1)

Why this query return more than one row? You can replace

(select generate_series(1, 1030) as id) t

with any table have field id

2 Answers 2

1

What I think is happening here is that the call to random() in your WHERE clause is happening once for each record examined. Instead, put the random logic into a subquery:

SELECT *
FROM
(
    SELECT generate_series(1, 1030) AS id
) t
WHERE id = (SELECT FLOOR(RANDOM() * 1030 + 1));

By the way, the reason the above trick works is because Postgres' optimizer will execute the subquery once and cache the result. If it didn't do this, then the above would still suffer from the same problem you are currently seeing.

Sign up to request clarification or add additional context in comments.

Comments

0

Because random() is defined as "volatile", which means it's evaluated for every row in the statement. If you want to pick one row, you need to "hide" the random function in a subselect:

select * 
from generate_series(1, 1030) as t(id) 
where id=(select floor(random() * 1030 + 1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.