Using JOIN for Suppression

/*************************************************
 * Complete example source code with sample data *
 *************************************************/

 /* Create our test data table -DROP script is commented out at the bottom of this script */
CREATE TABLE KeyTable([Key] INT NOT NULL) ON [PRIMARY]
CREATE TABLE SuppressionTable([Key] INT NOT NULL) ON [PRIMARY]

/* Load the Sample test Data into both tables */
INSERT INTO KeyTable ([Key]) VALUES
(1),(2),(3),(4),(5),(6)

INSERT INTO SuppressionTable ([Key]) VALUES
(5),(6),(7),(8),(9),(10)

/* First the bad way */
SELECT KeyTable.[Key]
FROM KeyTable
WHERE [Key] NOT IN (SELECT SuppressionTable.[Key] FROM SuppressionTable)

/* Now the results of the FULL OUTER JOIN */
SELECT KeyTable.[Key], SuppressionTable.[Key]
FROM KeyTable FULL OUTER JOIN SuppressionTable
ON KeyTable.[Key] = SuppressionTable.[Key]

/* Refine the FULL OUTER JOIN to give us the set we want */
SELECT KeyTable.[Key]
FROM KeyTable FULL OUTER JOIN SuppressionTable
ON KeyTable.[Key] = SuppressionTable.[Key]
WHERE SuppressionTable.[Key] IS NULL

/* Same results, but a little more efficient */
SELECT KeyTable.[Key]
FROM KeyTable LEFT OUTER JOIN SuppressionTable
ON KeyTable.[Key] = SuppressionTable.[Key]
WHERE SuppressionTable.[Key] IS NULL

/* The DROP Table scripts to remove the sample tables

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KeyTable]') AND type in (N'U'))
DROP TABLE [dbo].[KeyTable]

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SuppressionTable]') AND type in (N'U'))
DROP TABLE [dbo].[SuppressionTable]
*/

 

Author: Axe
I am a senior developer. Ride my motorcycle whenever I can. Love photography, hiking, camping, cooking, coding, and cheese cake!

Leave a Reply