Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a certain index exists in a table?

Tags:

sql-server

Something like this:

SELECT
* 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
WHERE CONSTRAINT_NAME ='FK_TreeNodesBinaryAssets_BinaryAssets'
and TABLE_NAME = 'TreeNodesBinaryAssets'

but for indexes.

like image 977
Lieven Cardoen Avatar asked Apr 22 '10 09:04

Lieven Cardoen


People also ask

How do you check if index exists on a table in Oracle?

You can find out the column_name and column_position of related index as follows. select table_name, index_name,column_name,column_position from dba_ind_columns where table_name='TABLE_NAME' and table_owner='TABLE_OWNER'; You can use the following Oracle views which gives you details about Indexes.

How do I find the indexes on a table in SQL Server?

sp_helpindex is a system stored procedure which lists the information of all the indexes on a table or view. This is the easiest method to find the indexes in a table. sp_helpindex returns the name of the index, description of the index and the name of the column on which the index was created.

How do you check if an index in an array exists?

To check if an array index exists, access the array at the specific index and check if the result is not equal to undefined . If the result is not equal to undefined the array index exists.


3 Answers

You can do it using a straight forward select like this:

SELECT * 
FROM sys.indexes 
WHERE name='YourIndexName' AND object_id = OBJECT_ID('Schema.YourTableName')
like image 123
AdaTheDev Avatar answered Oct 17 '22 23:10

AdaTheDev


For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY built-in function:

INDEXPROPERTY ( object_ID , index_or_statistics_name , property )  

The simplest usage is with the IndexID property:

If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null

If the index exists, the above will return its ID; if it doesn't, it will return NULL.

like image 21
Mr McGoo Avatar answered Oct 18 '22 00:10

Mr McGoo


AdaTheDEV, I used your syntax and created the following and why.

Problem: Process runs once a quarter taking an hour due to missing index.

Correction: Alter query process or Procedure to check for index and create it if missing... Same code is placed at the end of the query and procedure to remove index since it is not needed but quarterly. Showing Only drop syntax here

-- drop the index 
begin

  IF EXISTS (SELECT *  FROM sys.indexes  WHERE name='Index_Name' 
    AND object_id = OBJECT_ID('[SchmaName].[TableName]'))
  begin
    DROP INDEX [Index_Name] ON [SchmaName].[TableName];
  end

end
like image 80
Hank Freeman Avatar answered Oct 17 '22 23:10

Hank Freeman