Reputation: 245
Is there any better way to write the below query for optimize the performance.
INSERT INTO [dbo].[MBQ_All] ([Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ])
SELECT [Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ]
FROM dbo.MBQ_All_1
WHERE MBQ_All_1.Uniq NOT IN (
SELECT UNIQ
FROM dbo.MBQ_All
);
The table MBQ_All has more than 4,00,000 Rows and MBQ_All_1 has 2,00,000.
I'm using SQL Server 2008.
Upvotes: 0
Views: 47
Reputation: 11471
One of the options would be to have LEFT JOIN, but I am not sure if it will be faster:
INSERT INTO [dbo].[MBQ_All]
([Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS] ,[Store+whMBQ])
SELECT [Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ]
FROM dbo.MBQ_All_1 mbqN
LEFT JOIN MBQ_All mbqO ON mbqN.Uniq = mbqO.Uniq
WHERE mbqO.Uniq IS NULL
Upvotes: 1
Reputation: 3586
It's a clear case for MERGE statement:
MERGE [dbo].[MBQ_All] Tgt
USING [dbo].[MBQ_All_1] Src ON Tgt.Uniq = Src.Uniq
WHEN NOT MATCHED THEN
INSERT ( [Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max], [ADS], [Store+whMBQ])
VALUES (Src.[Uniq], Src.[StoreClass], Src.[Store], Src.[code], Src.[ExtendedDescription], Src.[ITEM_CLASS], Src.[SUPPLIER], Src.[Brands], Src.[Min], Src.[Max], Src.[ADS], Src.[Store+whMBQ]);
Upvotes: 2
Reputation: 583
Maybe try using NOT EXISTS:
INSERT INTO [dbo].[MBQ_All] ([Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ])
SELECT [Uniq], [StoreClass], [Store], [code], [ExtendedDescription],
[ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS] ,[Store+whMBQ]
FROM dbo.MBQ_All_1
WHERE NOT EXISTS (SELECT *
FROM dbo.MBQ_All
WHERE dbo.MBQ_All.UNIQ = MBQ_All_1.Uniq)
Upvotes: 2