skip to Main Content

I have randomize the order of records in a table using

SELECT * FROM TableA ORDER BY rand();

How do I seva the result table of this query?

When execute the query, I indeed got a shuffle order of the table.
But when I visit the page again, it shuffles again and the order change.
How do I save the result of just one shuffle?

2

Answers


  1. SQL tables do not have any inherent ordering. Unless you use an ORDER BY, the server is not even required to deliver the records in the same order twice in a row. If YOU need the records in some order, then you should create an "id" column of your own, and assign your order that way. Then you can do ORDER BY id.

    Login or Signup to reply.
  2. You can calculate a random integer and supply it as a seed for rand:

    SELECT * FROM TableA ORDER BY rand(481244482)
    

    This will likely return results in the same order, as long as the query plan doesn’t change and the data doesn’t change.

    If you are more explicit about which rows get which rand call

    select id, col1, col2 ...
    from (
        select id, col1, col2, ...
            rand(481244482) r
        from TableA
        order by TableA.id
    ) r
    order by r
    

    I believe this will guarantee the same results as long as the data doesn’t change.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search