Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get several records in select using random function in postgres?

This is my query:

SELECT id, geom from lars.punkt where id = (floor(random () * 99))::integer;

This is the result:

id    geom
40  "010100000000000000000010400000000000000000"
80  "010100000000000000000020400000000000000000"
88  "010100000000000000000020400000000000002040"

What is happening? I can also get 2 lines or zero lines.

I am expecting 1 line.

Is it the database which is "slow" or the code?

like image 936
Tengnagel Avatar asked Nov 17 '25 13:11

Tengnagel


1 Answers

I am expecting 1 line.

Random function is invoked per each row that is why you have zero, one or multiple matches. CROSS JOIN could be used to produce single random value that is used in WHERE condition:

SELECT id, geom 
from lars.punkt 
CROSS JOIN(SELECT (floor(random () * 99)::integer)) s(c)  --generate single random value
where id = s.c;

db<>fiddle demo - run multiple times

like image 93
Lukasz Szozda Avatar answered Nov 20 '25 01:11

Lukasz Szozda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!