Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-sql NOT IN with multiple columns

Tags:

tsql

I have a Microsoft SQL database, where i am trying to insert some data. I have a unique key on 4 columns and i want to insert data from multiple tables into this table while checking the data to make sure it will not violate the uniqueness of the key. If i was doing this on a single column, i would do a NOT IN, like so..

INSERT TABLE_A (FLD_1)
    SELECT FLD_1
        FROM TBL_B
        INNER JOIN TBL_C
            ON TBL_B.FLD_1 = TBL_C.FLD_1
    WHERE TBL_B.FLD_1 NOT IN
        (
        SELECT TBL_A.FLD_1 FROM TBL_A
        )

Any thoughts?

like image 242
Kyle Avatar asked Aug 04 '10 15:08

Kyle


People also ask

What can I use instead of not in SQL?

An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.

How use like operator for multiple columns in SQL?

multiple like statements can not be used with or directly. You have to use column name for each like statement. Use multiple like as mentioned below. I think the OP wants to search for the strings in multiple columns; your example searches in only one column.

Can you use != In SQL?

We can use both SQL Not Equal operators <> and != to do inequality test between two expressions. Both operators give the same output.

Which is faster not in or not exists?

NOT IN vs NOT EXISTS performance in SQL Server In this case, when the subquery returns even one null, NOT IN will not match any rows. Regarding performance aspects, SQL NOT EXISTS would be a better choice over SQL NOT IN. NOT EXISTS is significantly faster than NOT IN especially when the subquery result is very large.


1 Answers

Use NOT EXISTS instead since you have to deal with multiple columns.

http://www.techonthenet.com/sql/exists.php

EDIT:

Untested, but roughly it will be this:

SELECT FLD_1
FROM TBL_B
INNER JOIN TBL_C  ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE NOT EXISTS 
    (
    SELECT TBL_A.FLD_1 FROM TBL_A INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1
    )

For a multi-column check it would be roughly this:

SELECT FLD_1, FLD_2, FLD_3, FLD_4)
FROM TBL_B
INNER JOIN TBL_C  ON TBL_B.FLD_1 = TBL_C.FLD_1
WHERE NOT EXISTS 
    (
    SELECT TBL_A.FLD_1, TBL_A.FLD_2, TBL_A.FLD_3, TBL_A.FLD_4 
    FROM TBL_A 
    INNER JOIN TBL_B ON TBL_B.FLD1 = TBL_A.FLD1 AND 
                        TBL_B.FLD2 = TBL_A.FLD2 AND 
                        TBL_B.FLD3 = TBL_A.FLD3 AND 
                        TBL_B.FLD4 = TBL_A.FLD4 
    )
like image 113
Ian Jacobs Avatar answered Oct 01 '22 21:10

Ian Jacobs