SQL - improve NOT EXISTS query performance

前端 未结 7 1841
名媛妹妹
名媛妹妹 2021-02-07 09:08

Is there a way I can improve this kind of SQL query performance:

INSERT
INTO ...
WHERE NOT EXISTS(Validation...)

The problem is when I have ma

相关标签:
7条回答
  • 2021-02-07 09:37

    Outer Apply tends to work for me...

    instead of:

    from t1
    where not exists (select 1 from t2 where t1.something=t2.something)
    

    I'll use:

    from t1
    outer apply (
        select top 1 1 as found from t2 where t1.something=t2.something
    ) t2f
    where t2f.found is null
    
    0 讨论(0)
  • 2021-02-07 09:41
    insert into customers 
    select * 
    from newcustomers 
    where customerid not in (select customerid 
                             from customers)
    

    ..may be more efficient. As others have said, make sure you've got indexes on any lookup fields.

    0 讨论(0)
  • 2021-02-07 09:42

    Make sure you are searching on indexed columns, with no manipulation of the data within those columns (like substring etc.)

    0 讨论(0)
  • 2021-02-07 09:43

    If you can at all reduce your problem space, then you'll gain heaps of performance. Are you absolutely sure that every one of those rows in that table needs to be checked?

    The other thing you might want to try is a DELETE InsertTable FROM InsertTable INNER JOIN ExistingTable ON <Validation criteria> before your insert. However, your mileage may vary

    0 讨论(0)
  • 2021-02-07 09:46

    Try to replace the NOT EXISTS with a left outer join, it sometimes performs better in large data sets.

    0 讨论(0)
  • 2021-02-07 09:57

    Off the top of my head, you could try something like:

     TRUNCATE temptable
     INSERT INTO temptable ...
     INSERT INTO temptable ... 
     ...
     INSERT INTO realtable
     SELECT temptable.* FROM temptable
     LEFT JOIN realtable on realtable.key = temptable.key
     WHERE realtable.key is null
    
    0 讨论(0)
提交回复
热议问题