Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean T-SQL query I can use to verify an index has the right columns?

I am writing a DB upgrade script that will check to see if an index has the right two columns defined. If it doesn't, or if it only has one of them, then I will DROP it (is there a way to ALTER an index?) and then recreate it with both.

like image 280
skb Avatar asked Oct 23 '08 16:10

skb


People also ask

How do I check if a column is indexed in SQL Server?

Answers. In Management studio, go to the table you can see + symbol for the table click on that you can see Columns,Keys,Constraints,Triggers,Indexes,Statistics. If you have Indexes for the table after you click + symbol against Indexes you get the Index name with the column for which you declared index.

How do I find the index of a column in SQL Server?

You can use the sp_helpindex to view all the indexes of one table. And for all the indexes, you can traverse sys. objects to get all the indexes for each table. Only problem with this is that it only includes the index key columns, not the included columns.

How you can identify that index is not working properly on a table?

In Oracle SQL Developer, when you have SQL in the worksheet, there is a button "Explain Plan", you can also hit F10. After you execute Explain plan, it will show in the bottom view of SQL Developer. There is a column "OBJECT_NAME", it will tell you what index is being used.


1 Answers

I don't have a database immediately on-hand to test this, but you should be able to see if a column exists in an index by using the following IF EXISTS statement.

I'm not sure whether you can alter an index on the fly.

IF EXISTS
(
   SELECT MyIndex.Name AS IndexName, 
          Columns.name AS ColumnName 
   FROM sys.indexes MyIndex
   INNER JOIN sys.index_columns IndexColumns 
      ON  MyIndex.index_id = IndexColumns.index_id
      AND MyIndex.object_id = IndexColumns.object_id 
   INNER JOIN sys.columns Columns
      ON  Columns.column_id = IndexColumns.column_id 
      AND IndexColumns.object_id = Columns.object_id 
   WHERE Columns.name = 'ColumnName'
   AND MyIndex.Name='IX_MyIndexName'
)
like image 154
Ed Altorfer Avatar answered Nov 15 '22 06:11

Ed Altorfer