Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Created October 20, 2018 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosminpopescu14/29b19582c65ec874a88f8e749c2eec13 to your computer and use it in GitHub Desktop.
Save cosminpopescu14/29b19582c65ec874a88f8e749c2eec13 to your computer and use it in GitHub Desktop.
Pick random rows
/****** Script for slect random rwos. Works better with a large table and a good designed database ;) ******/
declare @rand bigint
declare @maxid int = (select max(id) from dbo.TODOS);
select @rand = abs((CHECKSUM(newid()))) % @maxid;
select *
from TODOS as t
where t.id >= @rand
order by t.StartDate
offset 10 rows
fetch next 5 rows only
-------------------------------------
DECLARE @row bigint=(
SELECT RAND(CHECKSUM(NEWID()))*SUM(rows) FROM sys.partitions
WHERE index_id IN (0, 1) AND [object_id]=OBJECT_ID('dbo.TODOS'));
SELECT *
FROM dbo.TODOS
ORDER BY (SELECT NULL)
OFFSET @row ROWS FETCH NEXT 5 ROWS ONLY;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment