Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How to find Unindexed FKs?

Author  Topic 

denis_the_thief
Aged Yak Warrior

596 Posts

Posted - 2009-11-17 : 09:17:03
Does anyone have a query that will return all Columns which are Foreign Keys, which are not indexed?

Or some other means of determining these Columns? We're having a few speed issues and sometimes we spend all this time tracing and then find out there is a missing index on a Foreign Key.

In any event, I'm going to start working on it and if I come up with something, I'll post it.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-17 : 13:08:13
Here's what I have in my toolbox:

--Create non clustered indexes for all foreign key references in the database
SELECT 'CREATE NONCLUSTERED INDEX [IX_' + tablename + '_' + columnname +'] ON [dbo].[' + tablename + '] ( [' + columnname + '] ASC)'
FROM
(
--Script all foreign key columns that are not already an index
-- SELECT
-- o.name AS tablename, cols.name AS columnName FROM sys.foreign_key_columns fc
-- inner join sys.objects o on fc.parent_object_id = o.object_id
-- inner join sys.columns cols on cols.object_id = o.object_id and fc.parent_column_id = cols.column_id
-- EXCEPT
SELECT o.name AS tablename, cols.name AS columnName FROM sys.index_columns icols
inner join sys.objects o on icols.object_Id = o.object_id
inner join sys.columns cols on cols.object_id = o.object_id and icols.column_id = cols.column_id
where icols.index_column_id = 1
) T
ORDER BY
tablename,
columnname


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

denis_the_thief
Aged Yak Warrior

596 Posts

Posted - 2009-11-18 : 13:58:50
Thankyou.

By giving me the create statments as well, I got even more than what I asked for.
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2009-11-18 : 14:29:14
That problem is a bit harder to solve if your foreign keys are made up of multiple columns because you need to make sure that you have an index that exactly matches each column in the FK in the same order, column by column.










CODO ERGO SUM
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-18 : 15:57:32
Agreed, I think I have a script that does that too, but the one I posted is what I quickly found in my "toolbox".

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page
   

- Advertisement -