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.

10
  • 1
    What have you already tried? Commented Apr 7, 2021 at 13:37
  • Have not any id in your table Commented Apr 7, 2021 at 13:38
  • 3
    Write the query that gets the last 10 added records, and then use that as a sub-query in a query that randomly orders the results and applies a limit of 1. Commented Apr 7, 2021 at 13:42
  • try ORDER BY RAND(). Commented Apr 7, 2021 at 13:43
  • 1
    Does this answer your question? How to request a random row in SQL? Commented Apr 7, 2021 at 13:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.