Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

PostgreSQL: how to select all records from one table that do not exist in another table?

$
0
0

Problem: I have two tables one is Employee, and another is Address, and I want to fetch all those records from Employee, which doesn't exist in the Address table.


--Employee

CREATETABLEemployee
(
       emp_idintGENERATEDALWAYSASIDENTITY,
       nametext
);

--Address
CREATETABLEaddress(
       addr_idintGENERATEDALWAYSASIDENTITY,
       emp_idint,
       address1text
);

INSERTINTOemployee(name)VALUES('Dilip'),('Harish'),('Manish'),('Akanksha'),('Avinash');
INSERTINTOaddress(emp_id,address1)VALUES(1,'Noida'),(2,'Delhi'),(3,'Gurugram');


There are several techniques to fetch the records from the employee table which does not exist in another table; I will try to explain some technical PostgreSQL queries.

Using LEFT JOIN in PostgreSQL

  

SELECTname
  FROMemployeeemp
  LEFTJOINaddressadrONemp.emp_id=adr.emp_id
  WHEREadr.emp_idISNULL;

  
Analysis query: Here I am applying LEFT JOIN that returns the left side table (employee) full records and right side table(address) as null if emp_id not matched, so I took advantage of this and applied WHERE clause on the right side table(address).

Using NOT EXISTS in PostgreSQL


For the above problem NOT EXISTS is a suitable solution because it is fastest in PostgreSQL than other solutions.


SELECTnameFROMemployeeemp
  WHERENOTEXISTS
       (
              SELECTemp_id
                     FROMaddress
                     WHEREemp_id=emp.emp_id
       );


Using NOT IN in PostgreSQL



SELECTname
  FROMemployee
WHEREemp_idNOTIN(
  SELECTDISTINCTemp_id
    FROMaddress);


         


Viewing all articles
Browse latest Browse all 265

Trending Articles