Tuesday, June 23, 2015

SQL Query to Find Unsaved Records

Hi guys,

            I have 2 sql tables. 1st one is main table and the  2nd one is for backup.
            Suppose if you get a situation, like you need to find out the records which are not backed up yet, then here I am posting a method to find out the remaining records.

Here I am creating 2 tables and inserting some values.


 CREATE TABLE Table1  
   ([SNo] int, [Item] varchar(50))  
   ;  
 INSERT INTO Table1  
   ([SNo], [Item])  
 VALUES  
   (1, 'A'),  
   (2, 'B'),  
   (3, 'C'),  
   (4, 'D'),  
   (5, 'E');  
 CREATE TABLE Table2  
   ([SNo] int, [Item] varchar(50));  
 INSERT INTO Table2  
   ([SNo], [Item])  
 VALUES  
   (1, 'A'),  
   (2, 'B'),  
   (3, 'C');  

You can get those records by using sub query like below.

 SELECT * FROM Table1 WHERE Sno NOT IN (Select SNo FROM Table2)  

 Result :
| SNo | Item |
|-----|------|
|   4 |    D |
|   5 |    E | 
You can also get the solution by using below query 
 select * from Table1 except select * from Table2  
Result : 

| SNo | Item |
|-----|------|
|   4 |    D |
|   5 |    E | 
I hope it would be helpful. 
Thanks 

LinkWithin

Related Posts Plugin for WordPress, Blogger...