Skip to content

Instantly share code, notes, and snippets.

@zarza
Last active March 10, 2018 15:41
Show Gist options
  • Save zarza/4ad3762fd91be65a12e2fb2bfd3e6b43 to your computer and use it in GitHub Desktop.
Save zarza/4ad3762fd91be65a12e2fb2bfd3e6b43 to your computer and use it in GitHub Desktop.
Fastest SQL to get random rows from MySQL in LARGE and small databases
# Ejemplo 1
SELECT * FROM post AS r1 JOIN (SELECT (RAND() * (SELECT MAX(postid) FROM post)) AS postid) AS r2 WHERE r1.postid >= r2.postid ORDER BY r1.postid ASC LIMIT 10
# Ejemplo 2
SELECT * FROM (SELECT * FROM `comprobantes` WHERE `ind-estado` = 'procesando' OR (`ind-estado` = 'rechazado' AND `respuesta-xml` IS NULL)) AS r1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM comprobantes)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment