Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding Overlapping Entries Between Certain Columns Of Two Tables

So I’ve tried searching and reading through many other posts before making this one.

Suppose you have two tables — table A and table B — where table B has more columns than A. Both share 2 columns: ID, location.

How would you:
(1) find any ID’s that overlap between the two tables
(2) if ID’s overlap, check if location overlaps

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for your help!

I tried to left join the larger table to the smaller one using a subquery, and then find the distinct number of ID’s that appeared.

>Solution :

For determining which IDs are in both tables, simply JOIN them on id. Then for checking if the locations match, use a boolean or case expression.

create table table1 (
  id integer,
  location varchar(5)
  );
  
create table table2 (
  id integer,
  location varchar(5)
  );
  
insert into table1 values 
(1, 'AAA'), 
(2, 'BBB'), 
(3, 'CCC'), 
(4, 'DDD');

insert into table2 values 
(1, 'AAA'), 
(2, 'EEEE'), 
(4, 'DDD');

select 
 a.id, 
 a.location = b.location as loc_match
from table1 a
join table2 b
  on a.id = b.id;
id loc_match
1 true
2 false
4 true

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading