Sample Header Ad - 728x90

postgresql random function returns duplicate results when order by random used in query

3 votes
2 answers
3936 views
I'm using postgresql 11.1-1 on Windows 10. On my system, if I run a query like the following, I will get a different number for each random column: postgres=# SELECT random() as sortOrder, random() as col2; sortorder | col2 -------------------+------------------- 0.607938482426107 | 0.121234225574881 (1 row) But if I add an ORDER BY clause, as shown below, then random returns the same random number each time for every row. postgres=# SELECT random() as sortOrder, random() as col2 FROM generate_series(0,1) ORDER BY sortOrder; sortorder | col2 -------------------+------------------- 0.100375576410443 | 0.100375576410443 0.170669795479625 | 0.170669795479625 (2 rows) I'm assuming there is a technical reason for this, but is it possible in this last query to get a different random value for each column? **Edit:** I may have oversimplified in my original question. The actual query I was attempting was more like the following: SELECT column1, random(), column2, random() FROM table1 ORDER BY random(); So, having an answer that can be combined with a table query is also important.
Asked by TMorgan (143 rep)
Mar 1, 2019, 10:44 PM
Last activity: Jun 30, 2024, 09:25 PM