Skip to content

Instantly share code, notes, and snippets.

@taspeotis
Created May 12, 2016 02:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save taspeotis/29dd509a2022cd43c7c54bc3c4b15162 to your computer and use it in GitHub Desktop.
Save taspeotis/29dd509a2022cd43c7c54bc3c4b15162 to your computer and use it in GitHub Desktop.
/*
https://connect.microsoft.com/SQLServer/feedback/details/683411
*/
IF NOT EXISTS ( SELECT TOP 1 NULL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'SinglePrimaryKey' )
BEGIN
CREATE TABLE SinglePrimaryKey
(
PrimaryId INT NOT NULL PRIMARY KEY
);
CREATE TABLE SingleForeignKey
(
PrimaryId INT NOT NULL PRIMARY KEY REFERENCES SinglePrimaryKey(PrimaryId)
);
CREATE TABLE CompositePrimaryKey
(
CompositeId INT NOT NULL,
PrimaryId INT NOT NULL,
CONSTRAINT PK_CompositePrimaryKey PRIMARY KEY (CompositeId, PrimaryId)
);
CREATE TABLE CompositeForeignKey
(
CompositeId INT NOT NULL,
PrimaryId INT NOT NULL,
CONSTRAINT PK_CompositeForeignKey PRIMARY KEY(CompositeId, PrimaryId),
CONSTRAINT FK_CompositeForeignKey_CompositePrimaryKey
FOREIGN KEY (CompositeId, PrimaryId) REFERENCES CompositePrimaryKey(CompositeId, PrimaryId)
);
END;
/* Execution plan => no join */
SELECT COUNT(*)
FROM SingleForeignKey
INNER JOIN SinglePrimaryKey
ON SingleForeignKey.PrimaryId = SinglePrimaryKey.PrimaryId;
/* Execution plan => redundant join */
SELECT COUNT(*)
FROM CompositeForeignKey
INNER JOIN CompositePrimaryKey
ON CompositeForeignKey.CompositeId = CompositePrimaryKey.CompositeId
AND CompositeForeignKey.PrimaryId = CompositePrimaryKey.PrimaryId;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment