1

My table has around 10k rows. How can I query select 1 random row of the last 10 added rows? I have a date column that is datetime of when the row was added.

This is one I use to get the last 10 rows:

SELECT id FROM mytable order by date desc LIMIT 10

I know I can do SELECT id FROM mytable ORDER BY RAND() LIMIT 1 but that just choose any random row, not from the last 10 rows.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Cindy
  • 13
  • 3

1 Answers1

2

One method uses a subquery:

SELECT t.*
FROM (SELECT id
      FROM mytable 
      ORDER BY date DESC
      LIMIT 10
     ) t
ORDER BY rand()
LIMIT 1;

This version uses the syntax conventions for MySQL.

You can use select * in the subquery to fetch the whole row.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786