Should I get rid of clustered indexes on Guid columns

后端 未结 9 537
遇见更好的自我
遇见更好的自我 2020-12-05 17:19

I am working on a database that usually uses GUIDs as primary keys.

By default SQL Server places a clustered index on primary key columns. I understand that this is

相关标签:
9条回答
  • 2020-12-05 18:03

    Yes, there's no point in having a clustered index on a random value.

    You probably do want clustered indexes SOMEWHERE in your database. For example, if you have a "Author" table and a "Book" table with a foreign key to "Author", and if you have a query in your application that says, "select ... from Book where AuthorId = ..", then you would be reading a set of books. It will be faster if those book are physically next to each other on the disk, so that the disk head doesn't have to bounce around from sector to sector gathering all the books of that author.

    So, you need to think about your application, the ways in which it queries the database.

    Make the changes.

    And then test, because you never know...

    0 讨论(0)
  • 2020-12-05 18:06

    While clustering on a GUID is normally a bad idea, be aware that GUIDs can under some circumstances cause fragmentation even in non-clustered indexes.

    Note that if you're using SQL Server 2005, the newsequentialid() function produces sequential GUIDs. This helps to prevent the fragmentation problem.

    I suggest using a SQL query like the following to measure fragmentation before making any decisions (excuse the non-ANSI syntax):

    SELECT OBJECT_NAME (ips.[object_id]) AS 'Object Name',
           si.name AS 'Index Name',
           ROUND (ips.avg_fragmentation_in_percent, 2) AS 'Fragmentation',
           ips.page_count AS 'Pages',
           ROUND (ips.avg_page_space_used_in_percent, 2) AS 'Page Density'
    FROM sys.dm_db_index_physical_stats 
         (DB_ID ('MyDatabase'), NULL, NULL, NULL, 'DETAILED') ips
    CROSS APPLY sys.indexes si
    WHERE si.object_id = ips.object_id
    AND   si.index_id = ips.index_id
    AND   ips.index_level = 0;
    
    0 讨论(0)
  • 2020-12-05 18:06

    It depends if you're doing a lot of inserts, or if you need very quick lookup by PK.

    0 讨论(0)
提交回复
热议问题