0

I'm looking for an efficient method of getting a single result from a SQL database randomly.

What I'm trying to accomplish is a "click here for new tip" where the tip is randomly selected from database. To simplify I don't care if this user has already seen this tip recently or ever before.

I realize I could get all tips then select one at random but that seems terribly inefficient, is there a built in or easy 'Random' function?

Thanks in advance

2 Answers 2

3

Will it work for you (I assume you are using SQLServer) ?

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

2 Comments

I saw this before posing the question, it just sounded terribly inefficient. I found this document after: petefreitag.com/item/466.cfm
Maybe you can answer my question, from the documentation I read it sounds like this creates a new temporary id for all entries in the table before choosing one, is that really scalable?
0

Simply use the RAND function on your database: http://msdn.microsoft.com/en-us/library/ms177610.aspx. Very efficient!

1 Comment

RAND() doesn't always work as required (see sql-server-helper.com/tips/generate-random-records.aspx)

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.