April 28, 2011 at 2:23 am
Hi there ,
Well i have a simple question . im working on a db where users send me SMS messages containing some context , after the day is over , i have to choose a winner based on some criteria of the sms body they have sent .
i was using SELECT TOP(1)* FROM TBL_WHATEVER ORDER BY NEWID() , but somehow i started feeling uncomfotable with this command because the Table gets really large and it takes time to select a random ,
Any suggestions ?
thanks in advance 😀
April 28, 2011 at 2:53 am
Something like this?
DECLARE @MaxValue INT, @MinValue INT
SET @MaxValue = 500
SET @MinValue = 1
SELECT * FROM (SELECT columns, ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber
FROM TBL_WHATEVER) t
WHERE t.rownumber = FLOOR(((@MaxValue + 1) - @MinValue) * RAND() + @MinValue)
April 28, 2011 at 3:31 am
If you have a sequential integer PK, then this is fast.
SELECT *
FROM TransactionDetail
WHERE TransactionDetailID = (SELECT ABS(CHECKSUM(NEWID()))%100000+1)
Replace 1000000 with the max ID in your table.
For better assistance in answering your questions, please read this[/url].
Hidden RBAR: Triangular Joins[/url] / The "Numbers" or "Tally" Table: What it is and how it replaces a loop[/url] Jeff Moden[/url]
April 28, 2011 at 4:46 am
thanks chris ! its much faster now .. considering that this table im working on has 11000000 rows right now .. and grows more every minute 🙂
April 29, 2011 at 12:10 pm
There is also the TABLESAMPLE clause:
http://msdn.microsoft.com/en-us/library/ms189108.aspx
From the article there is another way similar to ChrisM's method like this to get aprox 1% of rows:SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float)
/ CAST (0x7fffffff AS int)
July 22, 2011 at 5:04 am
I realize this is an old post but I have to ask... why would you feel that returning 110,000 (1% of the 11 million row table) would be a good thing instead of returning just the one row requested?
--Jeff Moden
Change is inevitable... Change for the better is not.
July 22, 2011 at 12:50 pm
It was just an example of other ways to get rangom rows.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply