SlideShare a Scribd company logo
1 of 26
Download to read offline
Efficient Pagination Using MySQL
                   Surat Singh Bhati (surat@yahoo-inc.com)
                    Rick James (rjames@yahoo-inc.com)


                               Yahoo Inc


Percona Performance Conference 2009
Outline

  1. Overview
     –    Common pagination UI pattern
     – Sample table and typical solution using OFFSET
     – Techniques to avoid large OFFSET
     – Performance comparison
     – Concerns




                                         -2-
Common Patterns




                  -3-
Basics


    First step toward having efficient pagination over large data set

     – Use index to filter rows (resolve WHERE)
     – Use same index to return rows in sorted order (resolve ORDER)




    Step zero
     – http://dev.mysql.com/doc/refman/5.1/en/mysql-indexes.html
     – http://dev.mysql.com/doc/refman/5.1/en/order-by-optimization.html
     – http://dev.mysql.com/doc/refman/5.1/en/limit-optimization.html




                                        -4-
Using Index


  KEY a_b_c (a, b, c)

  ORDER may get resolved using Index
       –   ORDER BY a
       –   ORDER BY a,b
       –   ORDER BY a, b, c
       –   ORDER BY a DESC, b DESC, c DESC


  WHERE and ORDER both resolved using index:
       –   WHERE a = const ORDER BY b, c
       –   WHERE a = const AND b = const ORDER BY c
       –   WHERE a = const     ORDER BY b, c
       –   WHERE a = const AND b > const ORDER BY b, c

  ORDER will not get resolved uisng index (file sort)
       –   ORDER BY a ASC, b DESC, c DESC /* mixed sort direction */
       –   WHERE g = const ORDER BY b, c        /* a prefix is missing */
       –   WHERE a = const ORDER BY c           /* b is missing */
       –   WHERE a = const ORDER BY a, d        /* d is not part of index */
                                               -5-
Sample Schema
  CREATE TABLE `message` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `user_id` int(11) NOT NULL,
    `content` text COLLATE utf8_unicode_ci NOT NULL,
    `create_time` int(11) NOT NULL,
    `thumbs_up` int(11) NOT NULL DEFAULT '0', /* Vote Count */
    PRIMARY KEY (`id`),
    KEY `thumbs_up_key` (`thumbs_up`,`id`)
  ) ENGINE=InnoDB

   mysql> show table status like 'message' G
           Engine: InnoDB
          Version: 10
       Row_format: Compact
             Rows: 50000040    /* 50 Million */
   Avg_row_length: 565
      Data_length: 28273803264 /* 26 GB */
     Index_length: 789577728   /* 753 MB */
        Data_free: 6291456
      Create_time: 2009-04-20 13:30:45

  Two use case:
  • Paginate by time, recent message one page one
  • Paginate by thumps_up, largest value on page one
                                          -6-
Typical Query

  1. Get the total records
     SELECT count(*) FROM message


  2. Get current page
     SELECT * FROM message
     ORDER BY id DESC LIMIT 0, 20


  •   http://domain.com/message?page=1
              • ORDER BY id DESC LIMIT 0,                 20

  •   http://domain.com/message?page=2
              • ORDER BY id DESC LIMIT 20,                 20

  •   http://domain.com/message?page=3
              • ORDER BY id DESC LIMIT 40,                 20


  Note: id is auto_increment, same as create_time order, no need to create index on create_time, save space



        –                                           -7-
Explain


  mysql> explain SELECT * FROM message
         ORDER BY id DESC
         LIMIT 10000, 20G
  ***************** 1. row **************
             id: 1
    select_type: SIMPLE
          table: message
           type: index
  possible_keys: NULL
            key: PRIMARY
        key_len: 4
            ref: NULL
           rows: 10020
          Extra:
  1 row in set (0.00 sec)
     – it can read rows using index scan and execution will stop as soon as it finds
       required rows.
     – LIMIT 10000, 20 means it has to read 10020 and throw away 10000 rows, then
       return next 20 rows.


                                          -8-
Performance Implications

     – Larger OFFSET is going to increase active data set, MySQL has to bring data
       in memory that is never returned to caller.
     – Performance issue is more visible when your have database that can't fit in
       main memory.
     – Small percentage of request with large OFFSET would be able to hit disk I/O
       Disk I/O bottleneck
     – In order to display “21 to 40 of 1000,000” , some one has to count 1000,000
       rows.




                                         -9-
Simple Solution

     – Do not display total records, does user really care?



     – Do not let user go to deep pages, redirect him
       http://en.wikipedia.org/wiki/Internet_addiction_disorder after certain number of
       pages




                                          - 10 -
Avoid Count(*)


  1. Never display total messages, let user see more message by clicking
     'next'



  2. Do not count on every request, cache it, display stale count, user do not
     care about 324533 v/s 324633


  3. Display 41 to 80 of Thousands


  4. Use pre calculated count, increment/decrement value as insert/delete
     happens.




                                       - 11 -
Solution to avoid offset

  1. Change User Interface
      – No direct jumps to Nth page



  2. LIMIT N is fine, Do not use LIMIT M,N
      – Provide extra clue about from where to start given page
      – Find the desired records using more restricted WHERE using given clue and
        ORDER BY and LIMIT N without OFFSET)




                                         - 12 -
Find the clue

   150
   111
   102                       Page One
   101
   100   <a href=”/page=2;last_seen=100;dir=next>Next</a>

   98    <a href=”/page=1;last_seen=98;dir=prev>Prev</a>
   97
   96                        Page Two
   95
   94    <a href=”/page=3;last_seen=94;dir=next>Next</a>

   93    <a href=”/page=3;last_seen=93;dir=prev>Prev</a>
   92
   91                         Page Three
   90
   89    <a href=”/page=4;last_seen=89;dir=prev>Next</a>




                                   - 13 -
Solution using clue

  Next Page:
  http://domain.com/forum?page=2&last_seen=100&dir=next

           WHERE id < 100 /* last_seen *
           ORDER BY id DESC LIMIT $page_size /* No OFFSET*/


  Prev Page:
  http://domain.com/forum?page=1&last_seen=98&dir=prev

           WHERE id > 98 /* last_seen *
           ORDER BY id ASC LIMIT $page_size /* No OFFSET*/


           Reverse given 10 rows before sending to user


                                 - 14 -
Explain

  mysql> explain
         SELECT * FROM message
         WHERE id < '49999961'
         ORDER BY id DESC LIMIT 20 G
  *************************** 1. row ***************************
             id: 1
    select_type: SIMPLE
          table: message
           type: range
  possible_keys: PRIMARY
            key: PRIMARY
        key_len: 4
            ref: NULL
           Rows: 25000020 /* ignore this */
          Extra: Using where
  1 row in set (0.00 sec)




                                   - 15 -
What about order by non unique values?


                         99
                         99
                         98    Page One
                         98
                         98
                         98
                         98
                         97    Page Two
                         97
                         10
  We can't do:
            WHERE thumbs_up < 98
            ORDER BY thumbs_up DESC /* It will return few seen rows */

  Can we say this:
            WHERE thumbs_up <= 98
            AND <extra_con>
            ORDER BY thumbs_up DESC

                                      - 16 -
Add more condition

  •   Consider thumbs_up as major number
       – if we have additional minor number, we can use combination of major & minor
         as extra condition




  •   Find additional column (minor number)
       – we can use id primary key as minor number




                                          - 17 -
Solution
                                     First Page
  SELECT thumbs_up, id
  FROM message
  ORDER BY thumbs_up DESC, id DESC
  LIMIT $page_size

  +-----------+----+
  | thumbs_up | id |
  +-----------+----+
  |        99 | 14 |
  |        99 | 2 |
  |        98 | 18 |
  |        98 | 15 |
  |        98 | 13 |
  +-----------+----+
                                     Next Page
  SELECT thumbs_up, id
  FROM message
  WHERE thumbs_up <= 98 AND (id < 13 OR thumbs_up < 98)
  ORDER BY thumbs_up DESC, id DESC
  LIMIT $page_size

  +-----------+----+
  | thumbs_up | id |
  +-----------+----+
  |        98 | 10 |
  |        98 | 6 |
  |        97 | 17 |
                                        - 18 -
Make it better..
   Query:


   SELECT * FROM message
   WHERE thumbs_up <= 98
            AND (id < 13 OR thumbs_up < 98)
   ORDER BY thumbs_up DESC, id DESC
   LIMIT 20


   Can be written as:


   SELECT m2.* FROM message m1, message m2
   WHERE m1.id = m2.id
            AND m1.thumbs_up <= 98
            AND (m1.id < 13 OR m1.thumbs_up < 98)
   ORDER BY m1.thumbs_up DESC, m1.id DESC
   LIMIT 20;

                                     - 19 -
Explain

  *************************** 1. row ***************************
             id: 1
    select_type: SIMPLE
          table: m1
           type: range
  possible_keys: PRIMARY,thumbs_up_key
            key: thumbs_up_key /* (thumbs_up,id) */
        key_len: 4
            ref: NULL
           Rows: 25000020 /*ignore this, we will read just 20 rows*/
          Extra: Using where; Using index /* Cover */
  *************************** 2. row ***************************
             id: 1
    select_type: SIMPLE
          table: m2
           type: eq_ref
  possible_keys: PRIMARY
            key: PRIMARY
        key_len: 4
            ref: forum.m1.id
           rows: 1
          Extra:

                                   - 20 -
Performance Gain (Primary Key Order)




                       - 21 -
Performance Gain (Secondary Key Order)




                      - 22 -
Throughput Gain


 •   Throughput Gain while hitting first 30 pages:

      – Using LIMIT OFFSET, N
          • 600 query/sec




      – Using LIMIT N (no OFFSET)
          • 3.7k query/sec




                                        - 23 -
Bonus Point

  Product issue with LIMIT M, N


     User is reading a page, in the mean time some records may be added to
     previous page.


     Due to insert/delete pages records are going to move forward/backward
     as rolling window:
      – User is reading messages on 4th page
      – While he was reading, one new message posted (it would be there on page
        one), all pages are going to move one message to next page.
      – User Clicks on Page 5
      – One message from page got pushed forward on page 5, user has to read it
        again


  No such issue with news approach

                                        - 24 -
Drawback

  Search Engine Optimization Expert says:
  Let bot reach all you pages with fewer number of deep dive


  Two Solutions:
  •   Read extra rows
       – Read extra rows in advance and construct links for few previous & next pages


  •   Use small offset
       – Do not read extra rows in advance, just add links for few past & next pages
         with required offset & last_seen_id on current page
       – Do query using new approach with small offset to display desired page
       –
                             file:///Users/surat/Desktop/Picture%2043.png




  Additional concern: Dynamic urls, last_seen is not constant over time.
                                                                            - 25 -
Thanks




  - 26 -

More Related Content

What's hot

Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationmysqlops
 
ClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTO
ClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTOClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTO
ClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTOAltinity Ltd
 
Red Team Revenge - Attacking Microsoft ATA
Red Team Revenge - Attacking Microsoft ATARed Team Revenge - Attacking Microsoft ATA
Red Team Revenge - Attacking Microsoft ATANikhil Mittal
 
Sql injection
Sql injectionSql injection
Sql injectionZidh
 
PostgreSQL 공간관리 살펴보기 이근오
PostgreSQL 공간관리 살펴보기 이근오PostgreSQL 공간관리 살펴보기 이근오
PostgreSQL 공간관리 살펴보기 이근오PgDay.Seoul
 
Mongodb - Scaling write performance
Mongodb - Scaling write performanceMongodb - Scaling write performance
Mongodb - Scaling write performanceDaum DNA
 
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱PgDay.Seoul
 
8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development SecuritySam Bowne
 
0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for IdentityNikhil Mittal
 
Commit Wait Class 대기시간 감소 방안_Wh oracle
Commit Wait Class 대기시간 감소 방안_Wh oracleCommit Wait Class 대기시간 감소 방안_Wh oracle
Commit Wait Class 대기시간 감소 방안_Wh oracle엑셈
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Irfad Imtiaz
 
Pwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShellPwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShellBeau Bullock
 
security misconfigurations
security misconfigurationssecurity misconfigurations
security misconfigurationsMegha Sahu
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performancejkeriaki
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectBlueinfy Solutions
 
Six Degrees of Domain Admin - BloodHound at DEF CON 24
Six Degrees of Domain Admin - BloodHound at DEF CON 24Six Degrees of Domain Admin - BloodHound at DEF CON 24
Six Degrees of Domain Admin - BloodHound at DEF CON 24Andy Robbins
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisArnab Mitra
 
[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기NHN FORWARD
 
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PGPgDay.Seoul
 

What's hot (20)

Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimization
 
ClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTO
ClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTOClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTO
ClickHouse on Kubernetes, by Alexander Zaitsev, Altinity CTO
 
Red Team Revenge - Attacking Microsoft ATA
Red Team Revenge - Attacking Microsoft ATARed Team Revenge - Attacking Microsoft ATA
Red Team Revenge - Attacking Microsoft ATA
 
Sql injection
Sql injectionSql injection
Sql injection
 
PostgreSQL 공간관리 살펴보기 이근오
PostgreSQL 공간관리 살펴보기 이근오PostgreSQL 공간관리 살펴보기 이근오
PostgreSQL 공간관리 살펴보기 이근오
 
Mongodb - Scaling write performance
Mongodb - Scaling write performanceMongodb - Scaling write performance
Mongodb - Scaling write performance
 
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
[pgday.Seoul 2022] POSTGRES 테스트코드로 기여하기 - 이동욱
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development Security
 
0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity0wn-premises: Bypassing Microsoft Defender for Identity
0wn-premises: Bypassing Microsoft Defender for Identity
 
Commit Wait Class 대기시간 감소 방안_Wh oracle
Commit Wait Class 대기시간 감소 방안_Wh oracleCommit Wait Class 대기시간 감소 방안_Wh oracle
Commit Wait Class 대기시간 감소 방안_Wh oracle
 
Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )Introduction to Cross Site Scripting ( XSS )
Introduction to Cross Site Scripting ( XSS )
 
Pwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShellPwning the Enterprise With PowerShell
Pwning the Enterprise With PowerShell
 
security misconfigurations
security misconfigurationssecurity misconfigurations
security misconfigurations
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open Redirect
 
Six Degrees of Domain Admin - BloodHound at DEF CON 24
Six Degrees of Domain Admin - BloodHound at DEF CON 24Six Degrees of Domain Admin - BloodHound at DEF CON 24
Six Degrees of Domain Admin - BloodHound at DEF CON 24
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기
 
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
 

Viewers also liked

Pagination Done the Right Way
Pagination Done the Right WayPagination Done the Right Way
Pagination Done the Right WayMarkus Winand
 
Modern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesModern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesMarkus Winand
 
A FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARD
A FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARDA FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARD
A FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARDTotango
 
[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?
[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?
[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?GangSeok Lee
 
SQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workSQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workMarkus Winand
 
[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼
[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼
[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼GangSeok Lee
 
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...Lukas Eder
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were PossibleLukas Eder
 
facebook architecture for 600M users
facebook architecture for 600M usersfacebook architecture for 600M users
facebook architecture for 600M usersJongyoon Choi
 
A simple example of Earned Value Management (EVM) in action
A simple example of Earned Value Management (EVM) in actionA simple example of Earned Value Management (EVM) in action
A simple example of Earned Value Management (EVM) in actionPlanisware
 

Viewers also liked (10)

Pagination Done the Right Way
Pagination Done the Right WayPagination Done the Right Way
Pagination Done the Right Way
 
Modern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesModern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial Databases
 
A FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARD
A FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARDA FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARD
A FRAMEWORK TO BUILD A KILLER CUSTOMER SUCESS SCORECARD
 
[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?
[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?
[2014 CodeEngn Conference 11] 최우석 - 자바스크립트 난독화 너네 뭐니?
 
SQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workSQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they work
 
[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼
[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼
[2014 CodeEngn Conference 11] 김기홍 - 빅데이터 기반 악성코드 자동 분석 플랫폼
 
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible
 
facebook architecture for 600M users
facebook architecture for 600M usersfacebook architecture for 600M users
facebook architecture for 600M users
 
A simple example of Earned Value Management (EVM) in action
A simple example of Earned Value Management (EVM) in actionA simple example of Earned Value Management (EVM) in action
A simple example of Earned Value Management (EVM) in action
 

Similar to Efficient Pagination Using MySQL Without Large OFFSET

Covering indexes
Covering indexesCovering indexes
Covering indexesMYXPLAIN
 
MySQL for business developer - Titouan BENOIT
MySQL for business developer - Titouan BENOITMySQL for business developer - Titouan BENOIT
MySQL for business developer - Titouan BENOITTitouan BENOIT
 
Introduction into MySQL Query Tuning
Introduction into MySQL Query TuningIntroduction into MySQL Query Tuning
Introduction into MySQL Query TuningSveta Smirnova
 
Building an Analytic Extension to MySQL with ClickHouse and Open Source
Building an Analytic Extension to MySQL with ClickHouse and Open SourceBuilding an Analytic Extension to MySQL with ClickHouse and Open Source
Building an Analytic Extension to MySQL with ClickHouse and Open SourceAltinity Ltd
 
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptxBuilding an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptxAltinity Ltd
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuRedis Labs
 
What's New In MySQL 5.6
What's New In MySQL 5.6What's New In MySQL 5.6
What's New In MySQL 5.6Abdul Manaf
 
Database Oracle Basic
Database Oracle BasicDatabase Oracle Basic
Database Oracle BasicKamlesh Singh
 
MySQL Query tuning 101
MySQL Query tuning 101MySQL Query tuning 101
MySQL Query tuning 101Sveta Smirnova
 
Troubleshooting MySQL Performance
Troubleshooting MySQL PerformanceTroubleshooting MySQL Performance
Troubleshooting MySQL PerformanceSveta Smirnova
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLanandology
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
SQL: tricks and cheats
SQL: tricks and cheatsSQL: tricks and cheats
SQL: tricks and cheatsMikalai Sitsko
 

Similar to Efficient Pagination Using MySQL Without Large OFFSET (20)

Covering indexes
Covering indexesCovering indexes
Covering indexes
 
MySQL for business developer - Titouan BENOIT
MySQL for business developer - Titouan BENOITMySQL for business developer - Titouan BENOIT
MySQL for business developer - Titouan BENOIT
 
Introduction into MySQL Query Tuning
Introduction into MySQL Query TuningIntroduction into MySQL Query Tuning
Introduction into MySQL Query Tuning
 
Optimizando MySQL
Optimizando MySQLOptimizando MySQL
Optimizando MySQL
 
Oracle
OracleOracle
Oracle
 
Raj mysql
Raj mysqlRaj mysql
Raj mysql
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
Building an Analytic Extension to MySQL with ClickHouse and Open Source
Building an Analytic Extension to MySQL with ClickHouse and Open SourceBuilding an Analytic Extension to MySQL with ClickHouse and Open Source
Building an Analytic Extension to MySQL with ClickHouse and Open Source
 
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptxBuilding an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
Building an Analytic Extension to MySQL with ClickHouse and Open Source.pptx
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
 
What's New In MySQL 5.6
What's New In MySQL 5.6What's New In MySQL 5.6
What's New In MySQL 5.6
 
SQL (1).pptx
SQL (1).pptxSQL (1).pptx
SQL (1).pptx
 
Database Oracle Basic
Database Oracle BasicDatabase Oracle Basic
Database Oracle Basic
 
MySQL Query tuning 101
MySQL Query tuning 101MySQL Query tuning 101
MySQL Query tuning 101
 
Troubleshooting MySQL Performance
Troubleshooting MySQL PerformanceTroubleshooting MySQL Performance
Troubleshooting MySQL Performance
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
 
MySQLinsanity
MySQLinsanityMySQLinsanity
MySQLinsanity
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
SQL: tricks and cheats
SQL: tricks and cheatsSQL: tricks and cheats
SQL: tricks and cheats
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Efficient Pagination Using MySQL Without Large OFFSET

  • 1. Efficient Pagination Using MySQL Surat Singh Bhati (surat@yahoo-inc.com) Rick James (rjames@yahoo-inc.com) Yahoo Inc Percona Performance Conference 2009
  • 2. Outline 1. Overview – Common pagination UI pattern – Sample table and typical solution using OFFSET – Techniques to avoid large OFFSET – Performance comparison – Concerns -2-
  • 4. Basics First step toward having efficient pagination over large data set – Use index to filter rows (resolve WHERE) – Use same index to return rows in sorted order (resolve ORDER) Step zero – http://dev.mysql.com/doc/refman/5.1/en/mysql-indexes.html – http://dev.mysql.com/doc/refman/5.1/en/order-by-optimization.html – http://dev.mysql.com/doc/refman/5.1/en/limit-optimization.html -4-
  • 5. Using Index KEY a_b_c (a, b, c) ORDER may get resolved using Index – ORDER BY a – ORDER BY a,b – ORDER BY a, b, c – ORDER BY a DESC, b DESC, c DESC WHERE and ORDER both resolved using index: – WHERE a = const ORDER BY b, c – WHERE a = const AND b = const ORDER BY c – WHERE a = const ORDER BY b, c – WHERE a = const AND b > const ORDER BY b, c ORDER will not get resolved uisng index (file sort) – ORDER BY a ASC, b DESC, c DESC /* mixed sort direction */ – WHERE g = const ORDER BY b, c /* a prefix is missing */ – WHERE a = const ORDER BY c /* b is missing */ – WHERE a = const ORDER BY a, d /* d is not part of index */ -5-
  • 6. Sample Schema CREATE TABLE `message` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `user_id` int(11) NOT NULL, `content` text COLLATE utf8_unicode_ci NOT NULL, `create_time` int(11) NOT NULL, `thumbs_up` int(11) NOT NULL DEFAULT '0', /* Vote Count */ PRIMARY KEY (`id`), KEY `thumbs_up_key` (`thumbs_up`,`id`) ) ENGINE=InnoDB mysql> show table status like 'message' G Engine: InnoDB Version: 10 Row_format: Compact Rows: 50000040 /* 50 Million */ Avg_row_length: 565 Data_length: 28273803264 /* 26 GB */ Index_length: 789577728 /* 753 MB */ Data_free: 6291456 Create_time: 2009-04-20 13:30:45 Two use case: • Paginate by time, recent message one page one • Paginate by thumps_up, largest value on page one -6-
  • 7. Typical Query 1. Get the total records SELECT count(*) FROM message 2. Get current page SELECT * FROM message ORDER BY id DESC LIMIT 0, 20 • http://domain.com/message?page=1 • ORDER BY id DESC LIMIT 0, 20 • http://domain.com/message?page=2 • ORDER BY id DESC LIMIT 20, 20 • http://domain.com/message?page=3 • ORDER BY id DESC LIMIT 40, 20 Note: id is auto_increment, same as create_time order, no need to create index on create_time, save space – -7-
  • 8. Explain mysql> explain SELECT * FROM message ORDER BY id DESC LIMIT 10000, 20G ***************** 1. row ************** id: 1 select_type: SIMPLE table: message type: index possible_keys: NULL key: PRIMARY key_len: 4 ref: NULL rows: 10020 Extra: 1 row in set (0.00 sec) – it can read rows using index scan and execution will stop as soon as it finds required rows. – LIMIT 10000, 20 means it has to read 10020 and throw away 10000 rows, then return next 20 rows. -8-
  • 9. Performance Implications – Larger OFFSET is going to increase active data set, MySQL has to bring data in memory that is never returned to caller. – Performance issue is more visible when your have database that can't fit in main memory. – Small percentage of request with large OFFSET would be able to hit disk I/O Disk I/O bottleneck – In order to display “21 to 40 of 1000,000” , some one has to count 1000,000 rows. -9-
  • 10. Simple Solution – Do not display total records, does user really care? – Do not let user go to deep pages, redirect him http://en.wikipedia.org/wiki/Internet_addiction_disorder after certain number of pages - 10 -
  • 11. Avoid Count(*) 1. Never display total messages, let user see more message by clicking 'next' 2. Do not count on every request, cache it, display stale count, user do not care about 324533 v/s 324633 3. Display 41 to 80 of Thousands 4. Use pre calculated count, increment/decrement value as insert/delete happens. - 11 -
  • 12. Solution to avoid offset 1. Change User Interface – No direct jumps to Nth page 2. LIMIT N is fine, Do not use LIMIT M,N – Provide extra clue about from where to start given page – Find the desired records using more restricted WHERE using given clue and ORDER BY and LIMIT N without OFFSET) - 12 -
  • 13. Find the clue 150 111 102 Page One 101 100 <a href=”/page=2;last_seen=100;dir=next>Next</a> 98 <a href=”/page=1;last_seen=98;dir=prev>Prev</a> 97 96 Page Two 95 94 <a href=”/page=3;last_seen=94;dir=next>Next</a> 93 <a href=”/page=3;last_seen=93;dir=prev>Prev</a> 92 91 Page Three 90 89 <a href=”/page=4;last_seen=89;dir=prev>Next</a> - 13 -
  • 14. Solution using clue Next Page: http://domain.com/forum?page=2&last_seen=100&dir=next WHERE id < 100 /* last_seen * ORDER BY id DESC LIMIT $page_size /* No OFFSET*/ Prev Page: http://domain.com/forum?page=1&last_seen=98&dir=prev WHERE id > 98 /* last_seen * ORDER BY id ASC LIMIT $page_size /* No OFFSET*/ Reverse given 10 rows before sending to user - 14 -
  • 15. Explain mysql> explain SELECT * FROM message WHERE id < '49999961' ORDER BY id DESC LIMIT 20 G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: message type: range possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: NULL Rows: 25000020 /* ignore this */ Extra: Using where 1 row in set (0.00 sec) - 15 -
  • 16. What about order by non unique values? 99 99 98 Page One 98 98 98 98 97 Page Two 97 10 We can't do: WHERE thumbs_up < 98 ORDER BY thumbs_up DESC /* It will return few seen rows */ Can we say this: WHERE thumbs_up <= 98 AND <extra_con> ORDER BY thumbs_up DESC - 16 -
  • 17. Add more condition • Consider thumbs_up as major number – if we have additional minor number, we can use combination of major & minor as extra condition • Find additional column (minor number) – we can use id primary key as minor number - 17 -
  • 18. Solution First Page SELECT thumbs_up, id FROM message ORDER BY thumbs_up DESC, id DESC LIMIT $page_size +-----------+----+ | thumbs_up | id | +-----------+----+ | 99 | 14 | | 99 | 2 | | 98 | 18 | | 98 | 15 | | 98 | 13 | +-----------+----+ Next Page SELECT thumbs_up, id FROM message WHERE thumbs_up <= 98 AND (id < 13 OR thumbs_up < 98) ORDER BY thumbs_up DESC, id DESC LIMIT $page_size +-----------+----+ | thumbs_up | id | +-----------+----+ | 98 | 10 | | 98 | 6 | | 97 | 17 | - 18 -
  • 19. Make it better.. Query: SELECT * FROM message WHERE thumbs_up <= 98 AND (id < 13 OR thumbs_up < 98) ORDER BY thumbs_up DESC, id DESC LIMIT 20 Can be written as: SELECT m2.* FROM message m1, message m2 WHERE m1.id = m2.id AND m1.thumbs_up <= 98 AND (m1.id < 13 OR m1.thumbs_up < 98) ORDER BY m1.thumbs_up DESC, m1.id DESC LIMIT 20; - 19 -
  • 20. Explain *************************** 1. row *************************** id: 1 select_type: SIMPLE table: m1 type: range possible_keys: PRIMARY,thumbs_up_key key: thumbs_up_key /* (thumbs_up,id) */ key_len: 4 ref: NULL Rows: 25000020 /*ignore this, we will read just 20 rows*/ Extra: Using where; Using index /* Cover */ *************************** 2. row *************************** id: 1 select_type: SIMPLE table: m2 type: eq_ref possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: forum.m1.id rows: 1 Extra: - 20 -
  • 21. Performance Gain (Primary Key Order) - 21 -
  • 22. Performance Gain (Secondary Key Order) - 22 -
  • 23. Throughput Gain • Throughput Gain while hitting first 30 pages: – Using LIMIT OFFSET, N • 600 query/sec – Using LIMIT N (no OFFSET) • 3.7k query/sec - 23 -
  • 24. Bonus Point Product issue with LIMIT M, N User is reading a page, in the mean time some records may be added to previous page. Due to insert/delete pages records are going to move forward/backward as rolling window: – User is reading messages on 4th page – While he was reading, one new message posted (it would be there on page one), all pages are going to move one message to next page. – User Clicks on Page 5 – One message from page got pushed forward on page 5, user has to read it again No such issue with news approach - 24 -
  • 25. Drawback Search Engine Optimization Expert says: Let bot reach all you pages with fewer number of deep dive Two Solutions: • Read extra rows – Read extra rows in advance and construct links for few previous & next pages • Use small offset – Do not read extra rows in advance, just add links for few past & next pages with required offset & last_seen_id on current page – Do query using new approach with small offset to display desired page – file:///Users/surat/Desktop/Picture%2043.png Additional concern: Dynamic urls, last_seen is not constant over time. - 25 -
  • 26. Thanks - 26 -