I am trying to prepare a query to insert new entries in a daily report into a separate table in a SQL Server database.
I have two tables as follows:
Table 1
id style_code location_code
-------------------------------
1 abcd IST
2 abcd DEL
3 wxyz DEL
Table 2
id style_code location_code
--------------------------------
1 abcd IST
2 wxyz IST
3 abcd DEL
4 wxyz DEL
I want to select all the rows in Table 2 where the combination of 'style_code' and 'location_id' DO NOT exist in Table 1. In this particular example, that would mean returning row 2 from Table 2 as 'wxyx & IST' do not exist in Table 1. (There is no relationship between the id columns. Table 2 is a temporary table)
I have been trying to put a join into a Select query with NOT IN, but I cannot seem to get the query to work correctly.
SELECT *
FROM [Table 2]
WHERE style_code NOT IN (SELECT style_code
FROM [Table 1]
INNER JOIN [Table 2] ON [Table 2].location_code = [Table 1].location_code);
I have a beginners understanding of SQL coding, but am no expert, and would appreciate any guidance.
You can use NOT EXISTS
and a correlated subquery.
SELECT *
FROM [Table 2] t2
WHERE NOT EXISTS (SELECT *
FROM [Table 1] t1
WHERE t1.style_code = t2.style_code
AND t1.location_code = t2.location_code);
You can use NOT EXISTS
:
SELECT *
FROM [Table 2]
WHERE NOT EXISTS (SELECT1
FROM [Table 1]
WHERE [Table 2].location_code = [Table 1].location_code AND
[Table 2].style_code = [Table 1].style_code
);
Some databases -- increasingly more and more of them -- do support multiple columns with IN
and NOT IN
. However, SQL Server is not among them.
In addition, I strongly recommend using NOT EXISTS
instead of NOT IN
when using a subquery. NOT IN
does not behave intuitively if any of the values returned by the subquery are NULL
. In that case, NOT IN
filters out all rows and the result set is empty.
Alternate way - You can achieve this using a LEFT OUTER JOIN
. This SQL may give you better performance than NOT EXISTS
or NOT IN
clauses.
select t2.id, t2.style_code, t2.location_code
from table_2 t2 left outer join table_1 t1
on t2.style_code = t1.style_code
and t2.location_code = t1.location_code
where t1.style_code is null;
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.