SQL Server heap v.s. clustered index

后端 未结 3 1916
难免孤独
难免孤独 2021-01-31 04:06

I am using SQL Server 2008. I know if a table has no clustered index, then it is called heap, or else the storage model is called clustered index (B-Tree).

I want to lea

3条回答
  •  耶瑟儿~
    2021-01-31 04:35

    Heaps are just tables without a clustering key - without a key that enforces a certain physical order.

    I would not really recommend having heaps at any time - except maybe if you use a table temporarily to bulk-load an external file, and then distribute those rows to other tables.

    In every other case, I would strongly recommend using a clustering key. SQL Server will use the Primary Key as the clustering key by default - which is a good choice, in most cases. UNLESS you use a GUID (UNIQUEIDENTIFIER) as your primary key, in which case using that as your clustering key is a horrible idea.

    See Kimberly Tripp's excellent blog posts GUIDs as Primary and/or the clustering key and The Clustered Index Debate Continues for excellent explanations why you should always have a clustering key, and why a GUID is a horrible clustering key.

    My recommendation would be:

    • in 99% of all cases try to use a INT IDENTITY as your primary key and let SQL Server make that the clustering key as well
    • exception #1: if you're bulk loading huge data amounts, you might be fine without a primary / clustering key for your temporary table
    • exception #2: if you must use a GUID as your primary key, then set your clustering key to a different column - preferably a INT IDENTITY - and I would even create a separate INT column just for that purpose, if no other column can be used

    Marc

提交回复
热议问题