Skip to main content
InterviewHubPRO
Section Overview
Q30

Question 30 of 50

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

60%
MySQL & InnoDB (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

How do you optimize Deep Pagination in MySQL (`LIMIT 1000000, 20`)?

senior LevelCode ExampleDatabases & SQLMySQL

In Simple Words: SELECT * FROM orders ORDER BY id LIMIT 1000000, 20; reads $1,000,020$ rows, discards the first million, and returns 20 rows (horribly slow!).

  • Deferred Join Optimization:
    sql
    SELECT * FROM orders o
    JOIN (
      SELECT id FROM orders ORDER BY id LIMIT 1000000, 20
    ) sub ON o.id = sub.id;
    
    The subquery scans only the primary key index in memory, and fetches full table rows only for the 20 target IDs!
  • Keyset Pagination (Seek Method - Best Practice): WHERE id > :last_seen_id ORDER BY id ASC LIMIT 20; (executes in $O(1)$ index seek).