Unreasonable Defaults: Primary Key as Clustering Key
Join the DZone community and get the full member experience.Join For Free
as you might have noticed—at least if you have read sql performance explained —i don’t think clustered indexes are as useful as most people believe. that is mainly because it is just too darn difficult to choose a good clustering key. as a matter of fact, choosing a good—the “right”—clustering key is almost impossible if there are more than one or two indexes on the table. the result is that most people just stick to the default—which is the primary key. unfortunately, this is almost always the worst possible choice.
in this article i explain the beast named clustered index and all it’s downsides. although this article uses sql server as demo database, the article is equally relevant for mysql/mariadb with innodb and the oracle database when using index-organized tables.
recap: what is a clustered index
the idea of clustered indexes is to store a complete table in a b-tree structure. if a table has a clustered index, it basically means the index is the table. a clustered index has a strict row order like any other b-tree index: it sorts the rows according to the index definition. in case of clustered indexes we call the columns that define the index order the clustering key. the alternative way to store a table is as a heap with no particular row order. clustered indexes have the advantage that they support very fast range scans. that is, they can fetch rows with the same (or similar) clustering key value quickly, because those rows are physically stored next to each other (clustered)—often in the same data page. when it comes to clustered indexes it is very important to understand that there is no separate place where the table is stored. the clustered index is the primary table store—thus you can have only one per table. that’s the definition of clustered indexes—it’s a contrast to heap tables.
there is, however, another contrast to clustered indexes: non-clustered indexes. just because of the naming, this is the more natural counterpart to clustered indexes to many people. from this perspective, the main difference is that querying a clustered index is always done as index-only scan. a non-clustered index, on the other hand, has just a sub-set of the table columns so it causes extra ios for getting the missing columns from the primary table store if needed. every row in a non-clustered index has a reference to the very same row in the primary table store for this purpose. in other words, using a non-clustered index generally involves resolving an extra level of indirection. generally, i said. in fact it is pretty easy to avoid this overhead by including all needed columns in the non-clustered index. in that case the database can find all the required data in the index and just doesn’t resolve the extra level of indirection. even non-clustered indexes can be used for index-only scans—making them as fast as clustered indexes. isn’t that what matters most?
the index-only scan is the important concept—not the clustered index.
later in the article, we’ll see that there is a duality among these aspects of clustered indexes: being a table store (in contrast to heap tables) or being an index that happens to have all table columns. unfortunately, this “table-index duality” can be as confusing as the wave-particle duality of light . hence, i’ll explicitly state which aspect appears at the time whenever necessary.
the costs of an extra level of indirection
when it comes to performance, an extra level of indirection is not exactly desirable because dereferencing takes time. the crucial point here is that the costs of dereferencing is greatly affected by the way the table is physically stored—either as heap table or as clustered index.
the following figures explain his phenomenon. they visualize the process to execute a query to fetch all
rows from 2012-05-23. the first figure uses a non-clustered index on
together with a heap table (= a table that doesn’t have a clustered index):
note that there is a single
index seek (non-clustered)
operation on the non-clustered index that causes two
into the heap table (one for each matched row). this operation reflects dereferencing the extra indirection to load the remaining columns from the primary table store. for heap tables, a non-clustered index uses the physical address (the so-called
) to refer to the very same row in the heap table. in the worst case the extra level of indirection causes one additional read access per row (neglecting forwarding).
now let’s look at the same scenario with a clustered index. more precisely, when using a non-clustered index in presence of a clustered-index on
—that is, the primary key as clustering key.
note that the definition of the index on the left hand side has not changed: it’s still a non-clustered index on
. nevertheless, the pure presence of the clustered index affects they way the non-clustered index refers to the primary table storage—which is the clustered index! unlike heap tables, clustered indexes are “living creatures” that move rows around as needed to maintain their properties (i.e.: the row order and tree balance). consequently the non-clustered index can’t use the physical address as reference anymore because it
could change at any time
. instead, it uses the clustering key
as reference. loading the missing columns from the primary table store (=clustered index) now involves a full b-tree traversal for each row. that are
extra ios per row as opposed to a single extra io in case of heap tables.
i also refer to this effect as the “clustered index penalty”. this penalty affects all non-clustered indexes on tables that have a clustered index.
for index-organized tables, the oracle database also stores the physical address of that row (=guess
rowid) along with the clustering key in the secondary indexes (=non-clustered indexes). if the row is found at this address, the database doesn’t need to perform the b-tree traversal. if not, however, it has performed one more io for nothing.
how bad is it?
now that we have seen that clustered indexes cause a considerable overhead for non-clustered indexes, you’ll probably like to know how bad it is? the theoretic answer has been given above—one io for the
compared to several ios for the
key lookup (clustered)
. however, as i learned the hard way when giving performance training, people tend to ignore, deny, or just don’t believe that fact. hence, i’ll show you a demo.
obviously, i’ll use two similar tables that just vary by the table storage they use (heap vs. clustered). the following listing shows the pattern to create these tables. the part in square brackets makes the difference to either use a heap table or clustered index as table store.
create table sales[nc] ( sale_id numeric not null, employee_id numeric not null, eur_value numeric(16,2) not null, sale_date date not null constraint salesnc_pk primary key [nonclustered] (sale_id), ); create index sales[nc]2 on sales[nc] (sale_date);
i’ve filled these tables with 10 million rows for this demo.
the next step is to craft a query that allows us to measure the performance impact.
select top 1 * from salesnc where sale_date > '2012-05-23' order by sale_date
the whole idea behind this query is to use the non-clustered index (hence filtering and ordering on
) to fetch a variable number of rows (hence
) from the primary table store (hence
to make sure it’s not executed as index-only scan).
now lets look what happens if we
set statistics io on
and run the query against the heap table:
scan count 1, logical reads 4, physical reads 0, read-ahead reads 0,…
the interesting figure is the logical reads count of four. there were no physical reads because i have executed the statement twice so it is executed from the cache. knowing that we have fetched a single row from a heap table, we can already conclude that the tree of the non-clustered index must have three levels. together with one more logical read to access the heap table we get the total of four logical reads we see above.
to verify this hypothesis, we can change the
clause to fetch two rows:
select top 2 * from salesnc where sale_date > '2012-05-23' order by sale_date
scan count 1, logical reads 5, physical reads 0, read-ahead reads 0,…
keep in mind that the lookup in the non-clustered index is essentially unaffected by this change—it still needs three logical reads if the second row happens to reside in the same index page—which is very likely. hence we see just one more logical read because of the second access to the heap table. this corresponds to the first figure above.
now let’s do the same test with the table that has (=is) a clustered index:
select top 1 * from sales where sale_date > '2012-05-23' order by sale_date
scan count 1, logical reads 8, physical reads 0, read-ahead reads 0,…
fetching a single row involves
logical reads—twice as many as before. if we assume that the non-clustered index has the same tree depth, it means that the
key lookup (clustered)
operation triggers five logical reads per row. let’s check that by fetching one more row:
select top 2 * from sales where sale_date > '2012-05-23' order by sale_date
scan count 1, logical reads 13, physical reads 0, read-ahead reads 0,…
as feared, fetching a second row triggers five more logical reads.
i’ve continued these test in 1/2/5-steps up to 100 rows to get more meaningful data:
|rows fetched||logical reads (heap)||logical reads (clustered)|
i’ve also fitted linear equations in the chart to see how the slope differs. the heap table matches the theoretic figures pretty closely (3 + 1 per row) but we see “only” four logical reads per row with the clustered index—not the five we would have expected from just fetching one and two rows.
who cares about logical reads anyway
logical reads are a fine benchmark because it yields reproducible results—independent of the current state of caches or other work done on the system. however, the above chart is still a very theoretic figure. four times as many logical reads does not automatically mean four times as slow. in all reality you’ll have a large part of the clustered index in the cache—at least the first few b-tree levels. that reduces the impact definitively. to see how it affects the impact, i conducted another test: measuring the execution time when running the queries from the cache. avoiding disk access is another way to get more or less reproducible figures that can be compared to each other.
again, i’ve used 1/2/5-steps but started at 10.000 rows—selecting fewer rows was too fast for the timer’s resolution. selecting more than 200.000 rows took extraordinarily long so that i believe the data didn’t fit into the cache anymore. hence i stopped collecting data there.
|rows fetched||time (heap)||time (clustered)|
from this test it seems that the “clustered index penalty” on the non-clustered index is more like three times as high as compared to using a heap table.
notwithstanding these results, is it perfectly possible that the real world caching leads to a “clustered index penalty” outside the here observed range in a production system.
what was the upside of clustered indexes again?
the upside of clustered indexes is that they can deliver subsequent rows quickly when accessed directly (not via a non-clustered index). in other words, they are fast if you use the clustering key to fetch several rows. remember that the primary key is the clustering key per default. in that case, it means fetching several rows via primary key—with a single query. hmm. well, you can’t do that with an equals filter. but how often do you use non-equals filters like
on the primary key? sometimes, maybe, but not that often that it makes sense to optimize the physical table layout for these queries
punish all other indexes with the “clustered index penalty.” that is really
luckily, sql server is quite flexible when it comes to clustered indexes. as opposed to mysql/innodb, sql server can use any column(s) as clustering key—even non-unique ones. you can choose the clustering key so it catches the most important range scan. remember that equals predicates (
) can also cause range scans (on non-unique columns). but beware: if you are using long columns and/or many columns as clustering key, they bloat all non-clustered indexes because each row in every non-clustered indexes contains the clustering key as reference to the primary table store. further, sql server makes non-unique clustering keys automatically unique by adding an extra column, which also bloats all non-clustered indexes. although this bloat will probably not affect the tree depth—thanks to the
logarithmic growth of the b-tree
—it might still hurt the cache-hit rate. that’s also why the “clustered index penalty” could be outside the range indicated by the tests above—in either way!
even if you are able to identify the clustering key that brings the most benefit for range scans, the overhead it introduces on the non-clustered indexes can void the gains again. as i said in the intro above, it is just too darn difficult to estimate the overall impact of these effects because the clustering key affects all indexes on the table in a pretty complex way. therefore, i’m very much in favour of using heap tables if possible and index-only scans when necessary. from this perspective, clustered indexes are just an additional space optimization in case the “clustered index penalty“ isn’t an issue—most importantly if you need only one index that is used for range scans.
some databases don’t support heap tables at all—most importantly mysql/mariadb with innodb and the azure database.
further there are configurations that can only use the primary key as clustering key—most importantly mysql/mariadb with innodb and oracle index-organized tables.
note that mysql/mariadb with innodb is on both lists. they don’t offer any alternative for what i referred to as “insane.” myisam being no alternative.
concluding: how many clustered indexes can a sql server table have?
to conclude this article, i’d like to demonstrate why it is a bad idea to consider the clustered index as the “silver bullet” that deserves all your thoughts about performance. this demo is simple. just take a second and think about the following question:
how many clustered indexes can a sql server table have?
i love to ask this question in my sql server performance trainings. it truly reveals the bad understanding of clustered indexes.
the first answer i get is usually is “one!” then i ask why i can’t have a second one. typical response: —silence—. after this article, you already know that a clustered index is not only an index, but also the primary table store. you can’t have two primary table stores. logical, isn’t it? next question: do i need to have a clustered index on every table? typical response: —silence— or “no” in a doubtful tone. i guess this is when the participants realize that i’m asking trick questions. however, you now know that sql server doesn’t need to have a clustered index on every table. in absence of a clustered index, sql server uses a heap as table store.
as per definition, the answer to the question is: “at most one.”
and now stop thinking about the clustered index as “silver bullet” and start putting the index-only scan into the focus. for that, i’ll rephrase the question slightly:
how many indexes on a sql server table can be queried as fast as a clustered index?
the only change to the original question is that it doesn’t focus on the clustered index as such anymore. instead it puts your focus on the positive effect you expect from a clustering index. the point in using a clustered index is not just to have a clustered index, it is about improving performance. so, let’s focus on that.
what makes the clustered index fast is that every (direct) access is an index-only scan. so the question essentially boils down to: “how many indexes can support an index-only scan?” and the simple answer is: as many as you like. all you need to do is to add all the required columns to a non-clustered index and
using it is as fast as though it was a clustered index. that’s what sql server’s
keyword of the
statement is for!
focusing on index-only scans instead of clustered indexes has several advantages:
you are not limited to one index. any index can be as fast as a clustered index.
includecolumns to a non-clustered index doesn’t affect anything else than this particular index. there is no penalty that hurts all other indexes!
you don’t need to add all table columns to a non-clustered index to enable an index-only scan. just add the columns that are relevant for the query you’d like to tune. that keeps the index small and can thus become even faster than a clustered index.
and the best part is: there is no mutual exclusion of index-only scans and clustered indexes. index-only scans work irrespective of the table storage. you can extend non-clustered indexes for index-only scans even if there is a clustered index. that’s also an easy way to avoid paying the “clustered index penalty” on non-clustered indexes.
because of the “clustered index penalty” the concept of the index-only scan is even more important when having a clustered index. really, if there is something like a “silver bullet”, it is the index-only scan—not the clustered index.
if you like my way to explain things, you’ll love sql performance explained .
Published at DZone with permission of Markus Winand, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.