I have a table which contains some links to photos in a few columns and I need to get a random photo from it.
SELECT photo_front, photo_left, photo_rear FROM photos ORDER BY RANDOM () LIMIT 1
gives me a 3 links. But can I get only 1 random out of it?
Advertisement
Answer
You can unpivot. For instance:
SELECT v.photo FROM photos p CROSS JOIN LATERAL (VALUES (photo_front), (photo_left), (photo_rear) ) v(photo) ORDER BY RANDOM() LIMIT 1;
If the columns can ever be NULL
, then you might want WHERE v.photo IS NOT NULL
.
I should note that using ORDER BY RANDOM()
is an expensive operation. You are using that in your query and so performance does not seem to be an issue.