简体   繁体   中英

Optimizing SQL INSERT query

I have recently been looking into possible ways how to optimize my INSERT queries. I am doing usually an INSERT with a batch size of 100.

My current example query:

IF EXISTS (SELECT * FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000',''))

BEGIN DELETE FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000','') END;

INSERT INTO [db].[Prices] VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi', NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1', GETUTCDATE(), convert(date,NULL,105), convert(date,NULL,105));

The possible optimizations that I have found from research are as following:

  • Replace * with fields
  • Replace WHERE with INNER JOIN

As this is rather new to me, any suggestions are welcome. It seems like the highest potential is in changing the core structure (IF EXISTS - DELETE - INSERT INTO).

Thank you for any help.

EXISTS will not necessary here you can use DELETE statement :

 DELETE 
 FROM [db].[Prices] 
 WHERE Source = 'Cars' AND TradeDate = CONVERT(DATETIME,'18-02-20', 5) AND 
       Contract = 'APR25' AND ProductCode = 'Audi' AND 
       Price = NULLIF('5.00000','') -- this will always 5.00000 `NULLIF` will not required
       AND Strike = '27.7500';

Then you can use INSERT Statement :

INSERT INTO [db].[Prices] (col1, col2, col3, . . .) -- Qualify all columns
    VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi',
             NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1', 
             GETUTCDATE(), convert(date,NULL,105), 
             convert(date,NULL,105), 04, 2025, NULL, NULL, '27.7500', '20', 
             NULL, '0.5',NULL
          );

You can remove nullif() & conversation style in where clause :

WHERE Source = 'Cars' AND TradeDate = '2020-02-18' AND 
      Contract = 'APR25' AND ProductCode = 'Audi' AND 
      Price = 5.00000 AND Strike = '27.7500';

You might need NULLIF() on Price :

NULLIF(Price, '')

Note : Always qualify all columns explicitly while using INSERT INTO . . INSERT INTO . . statement.

Consider using MERGE statement. Instead of DELETE followed by INSERT, you can do UPDATE / INSERT: https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM