Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>MySQL/InnoDB tables are always clustered (more on clustering <a href="http://use-the-index-luke.com/sql/clustering/index-organized-clustered-index" rel="nofollow noreferrer">here</a> and <a href="http://www.ovaistariq.net/521/understanding-innodb-clustered-indexes/" rel="nofollow noreferrer">here</a>).</p> <p>Since primary key also acts as a clustering key<sup>1</sup>, using the surrogate primary key means you are physically sorting the table in order that doesn't have a useful meaning for the client applications and cannot be utilized for querying.</p> <p>Furthermore, secondary indexes in clustered tables can be "fatter" than in heap-based tables and may require double lookup.</p> <p>For these reasons, you'd want to avoid surrogates and use more "natural" keys, similar to this:</p> <p><img src="https://i.stack.imgur.com/EeE9w.png" alt="enter image description here"></p> <p><em>(<code>{USER_ID, PICTURE_NO}</code> in table <code>VOTE</code> references the same-named fields in <code>PICTURE</code>. The <code>VOTE.VOTER_ID</code> references <code>USER.USER_ID</code>. Use integers for <code>*_ID</code> and <code>*_NO</code> fields if you can.)</em></p> <p>This physical model will enable extremely efficient querying for:</p> <ul> <li>Pictures of the given user (a simple range scan on <code>PICTURE</code> primary/clustering index).</li> <li>Votes on the given picture (a simple range scan on <code>VOTE</code> primary/clustering index). Depending on circumstances, this may actually be fast enough so you don't have to cache the sum in <code>PICTURE</code>.</li> </ul> <p>If you need votes of the given user, change the <code>VOTE</code> PK to: <code>{VOTER_ID, USER_ID, PICTURE_NO}</code>. If you need both (votes of picture and votes of user), keep the existing PK, but create a <a href="http://use-the-index-luke.com/sql/glossary/covering-index" rel="nofollow noreferrer">covering</a> index on <code>{VOTER_ID, USER_ID, PICTURE_NO, VOTE_VALUE}</code>.</p> <hr> <p><em><sup>1</sup> In InnoDB. There are DBMSes (such as MS SQL Server) where clustering key can differ from primary.</em></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload