functions/Find-DbaDuplicateIndex.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
function Find-DbaDuplicateIndex {
    <#
  .SYNOPSIS
   Find duplicate and overlapping indexes.
 
  .DESCRIPTION
   This command will help you to find duplicate and overlapping indexes on a database or a list of databases.
 
   On SQL Server 2008 and higher, the IsFiltered property will also be checked
 
   Also tells how much space you can save by dropping the index.
 
   We show the type of compression so you can make a more considered decision.
 
   For now only supports CLUSTERED and NONCLUSTERED indexes.
 
   You can select the indexes you want to drop on the gridview and when clicking OK, the DROP statement will be generated.
 
   Output:
    TableName
    IndexName
    KeyColumns
    IncludedColumns
    IndexSizeMB
    IndexType
    CompressionDescription (When 2008+)
    [RowCount]
    IsDisabled
    IsFiltered (When 2008+)
    
        .PARAMETER SqlInstance
   The SQL Server you want to check for duplicate indexes.
         
        .PARAMETER SqlCredential
    Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:
 
   $cred = Get-Credential, then pass $cred object to the -SqlCredential parameter.
 
   Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.
 
   To connect as a different Windows user, run PowerShell as that user.
 
  .PARAMETER Database
   The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.
 
  .PARAMETER IncludeOverlapping
   If this switch is enabled, indexes which are partially duplicated will be returned.
 
   Example: If the first key column is the same between two indexes, but one has included columns and the other not, this will be shown.
 
  .PARAMETER WhatIf
   If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
 
  .PARAMETER Confirm
   If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
 
  .PARAMETER Force
   If this switch is enabled, the DROP statement(s) will be executed instead of being written to the output file.
 
  .PARAMETER EnableException
   By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
   This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
   Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
    
  .NOTES
   Author: Claudio Silva (@ClaudioESSilva)
   dbatools PowerShell module (https://dbatools.io, clemaire@gmail.com)
   Copyright (C) 2016 Chrissy LeMaire
   License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
  .LINK
   https://dbatools.io/Find-DbaDuplicateIndex
 
  .EXAMPLE
   Find-DbaDuplicateIndex -SqlInstance sql2005 -FilePath C:\temp\sql2005-DuplicateIndexes.sql
 
   Generates SQL statements to drop the selected duplicate indexes in server "sql2005" and writes them to the file "C:\temp\sql2005-DuplicateIndexes.sql"
 
  .EXAMPLE
   Find-DbaDuplicateIndex -SqlInstance sql2005 -FilePath C:\temp\sql2005-DuplicateIndexes.sql -Append
 
   Generates SQL statements to drop the selected duplicate indexes and writes/appends them to the file "C:\temp\sql2005-DuplicateIndexes.sql"
    
  .EXAMPLE
   Find-DbaDuplicateIndex -SqlInstance sqlserver2014a -SqlCredential $cred
     
   Finds exact duplicate indexes on all user databases present on sqlserver2014a, using SQL authentication.
    
  .EXAMPLE
   Find-DbaDuplicateIndex -SqlInstance sqlserver2014a -Database db1, db2
 
   Finds exact duplicate indexes on the db1 and db2 databases.
 
  .EXAMPLE
   Find-DbaDuplicateIndex -SqlInstance sqlserver2014a -IncludeOverlapping
 
   Finds both duplicate and overlapping indexes on all user databases.
    
 #>

    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [switch]$IncludeOverlapping,
        [switch]$EnableException
    )
    
    begin {
        $exactDuplicateQuery2005 = "
   WITH CTE_IndexCols
   AS (
    SELECT i.[object_id]
     ,i.index_id
     ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
     ,OBJECT_NAME(i.[object_id]) AS TableName
     ,NAME AS IndexName
     ,ISNULL(STUFF((
        SELECT ', ' + col.NAME + ' ' + CASE
          WHEN idxCol.is_descending_key = 1
           THEN 'DESC'
          ELSE 'ASC'
          END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
        INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
         AND i.index_id = idxCol.index_id
         AND idxCol.is_included_column = 0
        ORDER BY idxCol.key_ordinal
        FOR XML PATH('')
        ), 1, 2, ''), '') AS KeyColumns
     ,ISNULL(STUFF((
        SELECT ', ' + col.NAME + ' ' + CASE
          WHEN idxCol.is_descending_key = 1
           THEN 'DESC'
          ELSE 'ASC'
          END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
        INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
         AND i.index_id = idxCol.index_id
         AND idxCol.is_included_column = 1
        ORDER BY idxCol.key_ordinal
        FOR XML PATH('')
        ), 1, 2, ''), '') AS IncludedColumns
     ,i.[type_desc] AS IndexType
     ,i.is_disabled AS IsDisabled
    FROM sys.indexes AS i
    WHERE i.index_id > 0 -- Exclude HEAPS
     AND i.[type_desc] IN (
      'CLUSTERED'
      ,'NONCLUSTERED'
      )
     AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
    )
    ,CTE_IndexSpace
   AS (
    SELECT s.[object_id]
     ,s.index_id
     ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
     ,SUM(p.[rows]) AS [RowCount]
    FROM sys.dm_db_partition_stats AS s
    INNER JOIN sys.partitions p WITH (NOLOCK) ON s.[partition_id] = p.[partition_id]
     AND s.[object_id] = p.[object_id]
     AND s.index_id = p.index_id
    WHERE s.index_id > 0 -- Exclude HEAPS
     AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
    GROUP BY s.[object_id]
     ,s.index_id
    )
   SELECT DB_NAME() AS DatabaseName
    ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
    ,CI1.IndexName
    ,CI1.KeyColumns
    ,CI1.IncludedColumns
    ,CI1.IndexType
    ,CSPC.IndexSizeMB
    ,CSPC.[RowCount]
    ,CI1.IsDisabled
   FROM CTE_IndexCols AS CI1
   INNER JOIN CTE_IndexSpace AS CSPC ON CI1.[object_id] = CSPC.[object_id]
    AND CI1.index_id = CSPC.index_id
   WHERE EXISTS (
     SELECT 1
     FROM CTE_IndexCols CI2
     WHERE CI1.SchemaName = CI2.SchemaName
      AND CI1.TableName = CI2.TableName
      AND CI1.KeyColumns = CI2.KeyColumns
      AND CI1.IncludedColumns = CI2.IncludedColumns
      AND CI1.IndexName <> CI2.IndexName
     )"

        
        $overlappingQuery2005 = "
   WITH CTE_IndexCols
   AS (
    SELECT i.[object_id]
     ,i.index_id
     ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
     ,OBJECT_NAME(i.[object_id]) AS TableName
     ,NAME AS IndexName
     ,ISNULL(STUFF((
        SELECT ', ' + col.NAME + ' ' + CASE
          WHEN idxCol.is_descending_key = 1
           THEN 'DESC'
          ELSE 'ASC'
          END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
        INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
         AND i.index_id = idxCol.index_id
         AND idxCol.is_included_column = 0
        ORDER BY idxCol.key_ordinal
        FOR XML PATH('')
        ), 1, 2, ''), '') AS KeyColumns
     ,ISNULL(STUFF((
        SELECT ', ' + col.NAME + ' ' + CASE
          WHEN idxCol.is_descending_key = 1
           THEN 'DESC'
          ELSE 'ASC'
          END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
        INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
         AND i.index_id = idxCol.index_id
         AND idxCol.is_included_column = 1
        ORDER BY idxCol.key_ordinal
        FOR XML PATH('')
        ), 1, 2, ''), '') AS IncludedColumns
     ,i.[type_desc] AS IndexType
     ,i.is_disabled AS IsDisabled
    FROM sys.indexes AS i
    WHERE i.index_id > 0 -- Exclude HEAPS
     AND i.[type_desc] IN (
      'CLUSTERED'
      ,'NONCLUSTERED'
      )
     AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
    )
    ,CTE_IndexSpace
   AS (
    SELECT s.[object_id]
     ,s.index_id
     ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
     ,SUM(p.[rows]) AS [RowCount]
    FROM sys.dm_db_partition_stats AS s
    INNER JOIN sys.partitions p WITH (NOLOCK) ON s.[partition_id] = p.[partition_id]
     AND s.[object_id] = p.[object_id]
     AND s.index_id = p.index_id
    WHERE s.index_id > 0 -- Exclude HEAPS
     AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
    GROUP BY s.[object_id]
     ,s.index_id
    )
   SELECT DB_NAME() AS DatabaseName
    ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
    ,CI1.IndexName
    ,CI1.KeyColumns
    ,CI1.IncludedColumns
    ,CI1.IndexType
    ,CSPC.IndexSizeMB
    ,CSPC.[RowCount]
    ,CI1.IsDisabled
   FROM CTE_IndexCols AS CI1
   INNER JOIN CTE_IndexSpace AS CSPC ON CI1.[object_id] = CSPC.[object_id]
    AND CI1.index_id = CSPC.index_id
   WHERE EXISTS (
     SELECT 1
     FROM CTE_IndexCols CI2
     WHERE CI1.SchemaName = CI2.SchemaName
      AND CI1.TableName = CI2.TableName
      AND (
       (
        CI1.KeyColumns LIKE CI2.KeyColumns + '%'
        AND SUBSTRING(CI1.KeyColumns, LEN(CI2.KeyColumns) + 1, 1) = ' '
        )
       OR (
        CI2.KeyColumns LIKE CI1.KeyColumns + '%'
        AND SUBSTRING(CI2.KeyColumns, LEN(CI1.KeyColumns) + 1, 1) = ' '
        )
       )
      AND CI1.IndexName <> CI2.IndexName
     )"

        
        # Support Compression 2008+
        $exactDuplicateQuery = "
   WITH CTE_IndexCols
   AS (
    SELECT i.[object_id]
     ,i.index_id
     ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
     ,OBJECT_NAME(i.[object_id]) AS TableName
     ,NAME AS IndexName
     ,ISNULL(STUFF((
        SELECT ', ' + col.NAME + ' ' + CASE
          WHEN idxCol.is_descending_key = 1
           THEN 'DESC'
          ELSE 'ASC'
          END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
        INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
         AND i.index_id = idxCol.index_id
         AND idxCol.is_included_column = 0
        ORDER BY idxCol.key_ordinal
        FOR XML PATH('')
        ), 1, 2, ''), '') AS KeyColumns
     ,ISNULL(STUFF((
        SELECT ', ' + col.NAME + ' ' + CASE
          WHEN idxCol.is_descending_key = 1
           THEN 'DESC'
          ELSE 'ASC'
          END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
        INNER JOIN sys.columns col ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
         AND i.index_id = idxCol.index_id
         AND idxCol.is_included_column = 1
        ORDER BY idxCol.key_ordinal
        FOR XML PATH('')
        ), 1, 2, ''), '') AS IncludedColumns
     ,i.[type_desc] AS IndexType
     ,i.is_disabled AS IsDisabled
     ,i.has_filter AS IsFiltered
    FROM sys.indexes AS i
    WHERE i.index_id > 0 -- Exclude HEAPS
     AND i.[type_desc] IN (
      'CLUSTERED'
      ,'NONCLUSTERED'
      )
     AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
    )
    ,CTE_IndexSpace
   AS (
    SELECT s.[object_id]
     ,s.index_id
     ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
     ,SUM(p.[rows]) AS [RowCount]
     ,p.data_compression_desc AS CompressionDescription
    FROM sys.dm_db_partition_stats AS s
    INNER JOIN sys.partitions p WITH (NOLOCK) ON s.[partition_id] = p.[partition_id]
     AND s.[object_id] = p.[object_id]
     AND s.index_id = p.index_id
    WHERE s.index_id > 0 -- Exclude HEAPS
     AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
    GROUP BY s.[object_id]
     ,s.index_id
     ,p.data_compression_desc
    )
   SELECT DB_NAME() AS DatabaseName
    ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
    ,CI1.IndexName
    ,CI1.KeyColumns
    ,CI1.IncludedColumns
    ,CI1.IndexType
    ,CSPC.IndexSizeMB
    ,CSPC.CompressionDescription
    ,CSPC.[RowCount]
    ,CI1.IsDisabled
    ,CI1.IsFiltered
   FROM CTE_IndexCols AS CI1
   INNER JOIN CTE_IndexSpace AS CSPC ON CI1.[object_id] = CSPC.[object_id]
    AND CI1.index_id = CSPC.index_id
   WHERE EXISTS (
     SELECT 1
     FROM CTE_IndexCols CI2
     WHERE CI1.SchemaName = CI2.SchemaName
      AND CI1.TableName = CI2.TableName
      AND CI1.KeyColumns = CI2.KeyColumns
      AND CI1.IncludedColumns = CI2.IncludedColumns
      AND CI1.IsFiltered = CI2.IsFiltered
      AND CI1.IndexName <> CI2.IndexName
     )"

        
        $overlappingQuery = "
   WITH CTE_IndexCols AS
   (
    SELECT
      i.[object_id]
      ,i.index_id
      ,OBJECT_SCHEMA_NAME(i.[object_id]) AS SchemaName
      ,OBJECT_NAME(i.[object_id]) AS TableName
      ,Name AS IndexName
      ,ISNULL(STUFF((SELECT ', ' + col.NAME + ' ' + CASE
                 WHEN idxCol.is_descending_key = 1 THEN 'DESC'
                 ELSE 'ASC'
                END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
         INNER JOIN sys.columns col
         ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
        AND i.index_id = idxCol.index_id
        AND idxCol.is_included_column = 0
        ORDER BY idxCol.key_ordinal
      FOR XML PATH('')), 1, 2, ''), '') AS KeyColumns
      ,ISNULL(STUFF((SELECT ', ' + col.NAME + ' ' + CASE
                 WHEN idxCol.is_descending_key = 1 THEN 'DESC'
                 ELSE 'ASC'
                END -- Include column order (ASC / DESC)
        FROM sys.index_columns idxCol
         INNER JOIN sys.columns col
         ON idxCol.[object_id] = col.[object_id]
         AND idxCol.column_id = col.column_id
        WHERE i.[object_id] = idxCol.[object_id]
        AND i.index_id = idxCol.index_id
        AND idxCol.is_included_column = 1
        ORDER BY idxCol.key_ordinal
      FOR XML PATH('')), 1, 2, ''), '') AS IncludedColumns
      ,i.[type_desc] AS IndexType
      ,i.is_disabled AS IsDisabled
      ,i.has_filter AS IsFiltered
    FROM sys.indexes AS i
    WHERE i.index_id > 0 -- Exclude HEAPS
    AND i.[type_desc] IN ('CLUSTERED', 'NONCLUSTERED')
    AND OBJECT_SCHEMA_NAME(i.[object_id]) <> 'sys'
   ),
   CTE_IndexSpace AS
   (
   SELECT
      s.[object_id]
      ,s.index_id
      ,SUM(s.[used_page_count]) * 8 / 1024.0 AS IndexSizeMB
      ,SUM(p.[rows]) AS [RowCount]
      ,p.data_compression_desc AS CompressionDescription
    FROM sys.dm_db_partition_stats AS s
     INNER JOIN sys.partitions p WITH (NOLOCK)
     ON s.[partition_id] = p.[partition_id]
     AND s.[object_id] = p.[object_id]
     AND s.index_id = p.index_id    
    WHERE s.index_id > 0 -- Exclude HEAPS
     AND OBJECT_SCHEMA_NAME(s.[object_id]) <> 'sys'
    GROUP BY s.[object_id], s.index_id, p.data_compression_desc
   )
   SELECT
     DB_NAME() AS DatabaseName
     ,CI1.SchemaName + '.' + CI1.TableName AS 'TableName'
     ,CI1.IndexName
     ,CI1.KeyColumns
     ,CI1.IncludedColumns
     ,CI1.IndexType
     ,CSPC.IndexSizeMB
     ,CSPC.CompressionDescription
     ,CSPC.[RowCount]
     ,CI1.IsDisabled
     ,CI1.IsFiltered
   FROM CTE_IndexCols AS CI1
    INNER JOIN CTE_IndexSpace AS CSPC
    ON CI1.[object_id] = CSPC.[object_id]
    AND CI1.index_id = CSPC.index_id
   WHERE EXISTS (SELECT 1
       FROM CTE_IndexCols CI2
      WHERE CI1.SchemaName = CI2.SchemaName
       AND CI1.TableName = CI2.TableName
       AND (
          (CI1.KeyColumns like CI2.KeyColumns + '%' and SUBSTRING(CI1.KeyColumns,LEN(CI2.KeyColumns)+1,1) = ' ')
         OR (CI2.KeyColumns like CI1.KeyColumns + '%' and SUBSTRING(CI2.KeyColumns,LEN(CI1.KeyColumns)+1,1) = ' ')
        )
       AND CI1.IsFiltered = CI2.IsFiltered
       AND CI1.IndexName <> CI2.IndexName
      )"

    }
    process {
        if (Test-FunctionInterrupt) { return }
        
        foreach ($instance in $sqlinstance) {
            try {
                Write-Message -Level Verbose -Message "Connecting to $instance."
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            
            if ($database) {
                $databases = $server.Databases | Where-Object Name -in $database
            }
            else {
                $databases = $server.Databases | Where-Object IsAccessible -eq $true
            }
            
            foreach ($db in $databases) {
                try {
                    Write-Message -Level Verbose -Message "Getting indexes from database '$db'."
                    
                    $query = if ($server.versionMajor -eq 9) {
                        if ($IncludeOverlapping) { $overlappingQuery2005 }
                        else { $exactDuplicateQuery2005 }
                    }
                    else {
                        if ($IncludeOverlapping) { $overlappingQuery }
                        else { $exactDuplicateQuery }
                    }
                    
                    $db.Query($query)
                    
                }
                catch {
                    Stop-Function -Message "Query failure" -Target $db
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-SqlDuplicateIndex
    }
}