CREATE TABLE keyset_demo (a INTEGER, ts datetime, id integer primary key); go CREATE VIEW generator_16 AS SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15; go CREATE VIEW generator_256 AS SELECT ( ( hi.n * 16 ) + lo.n ) AS n FROM generator_16 lo, generator_16 hi; go CREATE VIEW generator_4k AS SELECT ( ( hi.n * 256 ) + lo.n ) AS n FROM generator_256 lo, generator_16 hi; go CREATE VIEW generator_64k AS SELECT ( ( hi.n * 256 ) + lo.n ) AS n FROM generator_256 lo, generator_256 hi; go CREATE FUNCTION random_date (@mindays int, @maxdays int) RETURNS VARCHAR(255) AS BEGIN DECLARE @rv date SET @rv = (SELECT GetDate() - rnd * (@maxdays-@mindays) - @mindays FROM rand_helper) RETURN @rv END GO CREATE VIEW rand_helper AS SELECT RND=RAND(); GO INSERT INTO keyset_demo SELECT n % 1000, dbo.random_date(0, 365), n FROM (SELECT ( hi.n * 65536 ) + lo.n AS n FROM generator_64k lo, generator_16 hi ) gen; go CREATE INDEX keyset_demo_ids ON keyset_demo (a, ts, id); go set statistics io on; SELECT * FROM keyset_demo WHERE a = 17 AND ts = "2015-12-12 08:41:05" and id > 547 OR a = 17 AND ts > "2015-12-12 08:41:05" OR a > 17 ORDER BY a, ts, id LIMIT 5 ; SELECT * FROM keyset_demo WHERE a >= 17 AND NOT (a = 17 AND ts <="2015-12-12 08:41:05") AND NOT (a = 17 AND ts = "2015-12-12 08:41:05" AND id <= 547) ORDER BY a, ts, id LIMIT 5 ; SELECT * FROM keyset_demo ORDER BY a, ts, id LIMIT 5 OFFSET 17833;