2

There is a table name Top_Up. Its current snapshot is: Top_Up Table

When I run query SELECT * FROM Top_Up WHERE Top_up_ID = (round(random() * 9 ) + 1); on it, I am getting random result. Sometimes it is returning with two tuples, sometimes no tuples and sometime one tuple.

To debug I run the query Select (round(random() * 9 ) + 1); and it is always returning only one tuple in the result.

Why I am getting this vague and random result?

1
  • Can you post the specific rows that you get (or at least the ID values) when you get more than one row? Also, why not just do a select * from Top_Up where Top_up_ID<=10 order by random() limit 1;? Commented Nov 7, 2012 at 22:04

1 Answer 1

3

Round is being calculated per row. Try this:

SELECT TOP 1 * FROM Top_Up ORDER BY (round(random() * 9 ) + 1);

If you run your test against your table you should see a much different result:

 Select (round(random() * 9 ) + 1) FROM Top_Up `

If you just want a random record I would go with:

SELECT TOP 1 * FROM Top_Up ORDER BY NEWID()
Sign up to request clarification or add additional context in comments.

1 Comment

The last query will scale better, where your original query would only select one from the first 10. Not sure if that was intentional or not though, which is why I offered both of them.

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.