--create parent table
CREATE TABLE dbo.ParentTable(
ParentTableID int NOT NULL IDENTITY
CONSTRAINT PK_ParentTable PRIMARY KEY CLUSTERED
,Column1 int NOT NULL
,Column2 varchar(100) NOT NULL
);
GO
--create a non-clustered covering index
CREATE UNIQUE NONCLUSTERED INDEX idx_ParentTable_ParentTableID
ON dbo.ParentTable(ParentTableID) INCLUDE(Column1);
GO
INSERT INTO dbo.ParentTable VALUES(1, 'some data');
INSERT INTO dbo.ParentTable VALUES(2, 'some data');
INSERT INTO dbo.ParentTable VALUES(3, 'some data');
GO
--create child table
CREATE TABLE dbo.ChildTable(
ChildTableID int NOT NULL IDENTITY
CONSTRAINT PK_ChildTable PRIMARY KEY CLUSTERED
,ParentTableID int NOT NULL
CONSTRAINT FK_ChildTable_ParentTable
FOREIGN KEY REFERENCES dbo.ParentTable(ParentTableID)
);
GO
INSERT INTO dbo.ChildTable VALUES(1);
INSERT INTO dbo.ChildTable VALUES(1);
INSERT INTO dbo.ChildTable VALUES(1);
INSERT INTO dbo.ChildTable VALUES(1);
INSERT INTO dbo.ChildTable VALUES(2);
INSERT INTO dbo.ChildTable VALUES(2);
INSERT INTO dbo.ChildTable VALUES(2);
INSERT INTO dbo.ChildTable VALUES(2);
INSERT INTO dbo.ChildTable VALUES(3);
INSERT INTO dbo.ChildTable VALUES(3);
INSERT INTO dbo.ChildTable VALUES(3);
INSERT INTO dbo.ChildTable VALUES(3);
GO
UPDATE STATISTICS dbo.ParentTable;
UPDATE STATISTICS dbo.ChildTable;
GO
--show the foreign key index binding
SELECT
fki.name
FROM sys.foreign_keys AS f
JOIN sys.indexes AS fki ON
fki.object_id = f.referenced_object_id
AND fki.index_id = f.key_index_id
WHERE
f.object_id = OBJECT_ID(N'dbo.FK_ChildTable_ParentTable');
GO
--this query uses the covering index instead of clustered PK index
SELECT p.ParentTableID, p.Column1
FROM dbo.ParentTable AS p
WHERE p.ParentTableID IN(1,2,3);
GO
|