Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update PSQL rows with different random values each

Tags:

postgresql

gis

I'm trying to batch update each row from a table, assigning them an individual location. This is the query I am using

UPDATE point SET location=
  ST_PointFromText('POINT(' || 
  (SELECT random()+5) || ' ' ||
  (SELECT random()+5) || ')', 4326) 
  WHERE parent_id=100;

The problem is that each row will then receive the exact same value.

like image 246
Felix Avatar asked Jul 03 '26 20:07

Felix


1 Answers

I found this article by Szymon Lipiński that touches on my problem. Here is how I fixed the query:

UPDATE point p SET location=
  ST_PointFromText('POINT(' || 
  ((SELECT random() WHERE p=p)+5) || ' ' ||
  ((SELECT random() where p=p)+5) || ')', 4326) 
  WHERE parent_id=100;

An outer dependency is needed in order to force PostgreSQL to reevaluate the expression each time.

like image 157
Felix Avatar answered Jul 06 '26 11:07

Felix



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!