I'm working on PostgreSQL with PHP.
Is it possible to select a particular number of random values in a column FROM table WHERE condition
instead of
select column FROM table WHERE condition
then convert them into an array and use array_rand()?
(I do not want to use this way because I will have millions of rows and selecting all values first then array_rand() is probably going to take a lot of time.)
Let's say I have a table like this:
name | items
-----------+------------
Ben | {dd,ab,aa}
-----------+------------
David | {dd,aa}
-----------+------------
Bryan | {aa,ab,cd}
-----------+------------
Glen | {cd}
-----------+------------
Edward | {aa,cd}
-----------+------------
Aaron | {dd,aa}
-----------+------------
..... (many many more)
Updates:
And I need to select the 10 random values in a column (or basically the 10 random rows) that match a condition (in this case would be @> ARRAY[aa]) without a sequential table scan or something that is time-consuming.
order by random() is going to take a lot of time as it has to deal with every row so I will go with a better solution instead.
order by random()is a perfectly valid solution, but its performance is poor and degrading progressively with "millions of rows", as therandom()function has to be evaluated of every row and then all rows have to be sorted before 10 can be returned. A performance nightmare! If you disclose more information about your case, I may be able to provide a much faster solution. I posted one recently here.random()is not a good idea. I've gone through the solution for select-random-rows-postgresql and it is pretty smart. However my case is different as I'm selecting random rows that match a condition instead of just any random row. I've elaborated my question :) and it would be great if you can help.while loopfor it if I go with the random id method and I am not sure how to do that. Or maybe there is a better solution.