Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : multiple WHERE NOT EXISTS clauses

I have about 2600 rows in the Load_Charges_IMPORT query that are not being inserted into the Load_Charges query.

I am trying to insure that no duplicate primary key entries are added. The primary key is established in the Load_Charges query as compound key (Charge Description + Charged Amount). No keys are set in the Load_Charges_IMPORT query, and this data is being imported from an excel document.

Can you tell me if there is something wrong with my code and why I am getting a response of 0 row(s) affected when I know there are 2600+ rows in Load_Charges_IMPORT.

INSERT INTO Load_Charges
    SELECT *
    FROM Load_Charges_IMPORT
    WHERE 
        NOT EXISTS (SELECT [Load ID]
                    FROM Load_Charges
                    WHERE Load_Charges_IMPORT.[Load ID] = Load_Charges.[Load ID])
        AND NOT EXISTS (SELECT [Charge Description]
                        FROM Load_Charges
                        WHERE Load_Charges_IMPORT.[Charge Description] = Load_Charges.[Charge Description])
        AND NOT EXISTS (SELECT [Charged Amount] 
                        FROM Load_Charges
                        WHERE Load_Charges_IMPORT.[Charged Amount] = Load_Charges.[Charged Amount]);
like image 930
C1-14MP Avatar asked Aug 26 '26 00:08

C1-14MP


2 Answers

Your EXISTS clause excludes all lines where any one of the conditions is TRUE, not only lines where all conditions are TRUE. Try this:

INSERT INTO Load_Charges

SELECT *

FROM Load_Charges_IMPORT

WHERE NOT EXISTS (
    SELECT * 
    FROM Load_Charges 
    WHERE Load_Charges_IMPORT.[Load ID]=Load_Charges.[Load ID]
    AND Load_Charges_IMPORT.[Charge Description]=Load_Charges.[Charge Description]
    AND Load_Charges_IMPORT.[Charged Amount]=Load_Charges.[Charged Amount]);
like image 164
Laughing Vergil Avatar answered Aug 27 '26 17:08

Laughing Vergil


Another way to address the issue is to use a series of LEFT JOINs, with a WHERE clause that excludes any matching record.

This is a shorter syntax, and avoids using a subquery.

INSERT INTO Load_Charges
SELECT imp.*
FROM 
    Load_Charges_IMPORT imp
    LEFT JOIN Load_Charges load1 ON load1.[Load ID] = imp.[Load ID]
    LEFT JOIN Load_Charges load2 ON load2.[Charge Description] = imp.[Charge Description]
    LEFT JOIN Load_Charges load3 ON load3.[Charged Amount]= imp.[Charged Amount]
WHERE load1.[Load ID] IS NULL AND load2.[Load ID] IS NULL AND load3.[Load ID] IS NULL
;

NB : this assumes that [Load ID] is a non-nullable field in the Load_Charges table. If not, any other non-nullable field can be used in the WHERE clause.

like image 20
GMB Avatar answered Aug 27 '26 17:08

GMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!