3
SELECT TOP 1 * 
FROM URLForPosting WITH(nolock) 
WHERE status = 0 
ORDER BY newid()

This is the query when I run in code I get timeout, even when I run it at SQL Server I get timeout.

However when I do this

SELECT TOP 1 * 
FROM URLForPosting WITH(nolock) 
WHERE status = 0 

It runs perfectly fine.

Also the first query was running fine until the records for the first 6 lacks records its has total 8 lack now it gives time out? I have created index on status.

Any suggestions?

10
  • The Order by newid() is a no-go. You sort by a value that is completely random and can't be indexed! What are you trying to achieve? Commented Nov 1, 2010 at 9:33
  • i am selecting links from the database and i want to get them randomly and when after completing my task i set there status to 1... Commented Nov 1, 2010 at 9:36
  • What do you suggest i do if i want to randomly pick values from the database not in a order Commented Nov 1, 2010 at 9:37
  • what do you mean by newid()? You should have column names in order by clause. Commented Nov 1, 2010 at 9:38
  • How many records in that table? Commented Nov 1, 2010 at 9:38

2 Answers 2

5

An alternative way to return a random record is to use TABLESAMPLE. See how this performs:

SELECT TOP 1 * 
FROM URLForPosting TABLESAMPLE(1) WITH(nolock) 
WHERE status=0 
ORDER BY newid()

TABLESAMPLE is available in SQL Server 2005 and later versions.

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

2 Comments

+1 because I never knew about this, but: If you specify a small number, such as 5, you might not receive results in the sample.
well i used this instead of newid() and it solved the problem SELECT top 1 * FROM URLForPosting WHERE status=0 and (ABS(CAST( (BINARY_CHECKSUM(*) * RAND()) as int)) % 100) < 1
0

Since it was running fine for when you had 600K records and is hanging at 800K it is likely that the inserts have caused your indexes to become fragmented. Get your DBA (or someone with db_owner rights) to run DBCC DBREINDEX(URLForPosting).

Or for versions 2005 upwards you can use ALTER INDEX REBUID.

1 Comment

well i used this instead of newid() and it solved the problem SELECT top 1 * FROM URLForPosting WHERE status=0 and (ABS(CAST( (BINARY_CHECKSUM(*) * RAND()) as int)) % 100) < 1

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.