Result occurs often with fast random select query I have this query to display 4 random photos on a website (I have it from here (when I asked for something faster than ORDER BY RAND())):

(SELECT   `p1`.`id`, `p1`.`url`, `p1`.`hits`, `p1`.`created_at`,
    `users`.`username`,
    `users`.`displayname`
FROM     pics p1
JOIN
        (SELECT ceil(rand() *
                (SELECT max(id)
                FROM   pics)) AS id
        ) AS p2
JOIN     users
ON       users.id = p1.user_id
WHERE    p1.id &gt;= p2.id
ORDER BY p1.id ASC limit 1
)
UNION ALL
(
SELECT   `p1`.`id`, `p1`.`url`, `p1`.`hits`, `p1`.`created_at`,
        `users`.`username`,
        `users`.`displayname`
FROM     pics p1
JOIN
        (SELECT ceil(rand() *
                (SELECT max(id)
                FROM   pics)) AS id
        ) AS p2
JOIN     users
ON       users.id = p1.user_id
WHERE    p1.id &gt;= p2.id
ORDER BY p1.id ASC limit 1
)
UNION ALL
(
SELECT   `p1`.`id`, `p1`.`url`, `p1`.`hits`, `p1`.`created_at`,
        `users`.`username`,
        `users`.`displayname`
FROM     pics p1
JOIN
        (SELECT ceil(rand() *
                (SELECT max(id)
                FROM   pics)) AS id
        ) AS p2
JOIN     users
ON       users.id = p1.user_id
WHERE    p1.id &gt;= p2.id
ORDER BY p1.id ASC limit 1
)
UNION ALL
(
SELECT   `p1`.`id`, `p1`.`url`, `p1`.`hits`, `p1`.`created_at`,
        `users`.`username`,
        `users`.`displayname`
FROM     pics p1
JOIN
        (SELECT ceil(rand() *
                (SELECT max(id)
                FROM   pics)) AS id
        ) AS p2
JOIN     users
ON       users.id = p1.user_id
WHERE    p1.id &gt;= p2.id
ORDER BY p1.id ASC limit 1
)


It is fast, but it seems, that one particular photo is displayed too often, about every 10th refresh of the page, or so. It has not id 1 (it has 1131), but is the 1st photo of a certain user. 

Could it be, that somehow gaps in the pics table could be the reason? I have no idea what else could be the reason.

edit:

SELECT id FROM pics WHERE id &lt; 1131 ORDER BY id DESC LIMIT 1; outputs this:

+-----+
| id  |
+-----+
| 923 |
+-----+
This has 8 'fast' ways to pick a random row from a table.

AI with gaps may be the best choice.

Or the 50/10 trick.

Add a FLOAT column may work well for you.

etc.