Wednesday, July 21, 2021

SQL Server : SQL scripts help - How to select all record from 1st table which is not present in 2nd table

How to select all record from 1st table which is not present in 2nd table:


Query:


 SELECT ID FROM tblEmployee WHERE ID NOT IN  (SELECT ID FROM tblPerson)


or 

SELECT name FROM table2 
WHERE NOT EXISTS 
    (SELECT * FROM table1 WHERE table1.name = table2.name)



To display all the contents of 2nd table which are not in 1st table without using NOT condition


Query:

1stly create 2 new sample tables and inserted some sample rows.

create table t1
( col1 int,
col2 int)


create table t2
( col1 int,
col2 int)

insert into t1 values(1,1)
insert into t1 values(2,2)



insert into t2 values(1,1)
insert into t2 values(2,2)

insert into t2 values(3,3)
insert into t2 values(4,4)


---to display table 2 entries which are not in table 1
--below bothe the queries worked for me
SELECT t2.col1
FROM t2
LEFT JOIN  t1 ON t2.col1 = t1.col1
WHERE t1.col1 IS NULL




SELECT * FROM T2
EXCEPT
SELECT a.* FROM T1 a
JOIN T2 b ON a.col1 = b.col1
=================================================================’

No comments:

Post a Comment

Top 15 SQL interview questions for 2-5 years experienced

  1. What is the difference between UNION and UNION ALL? UNION: To select related information from two tables UNION command is used. It is s...