Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify two columns of two different tables match exactly

When writing views and nesting views within deeper views I sometimes miss something and end up losing rows/data. How can I check that columns from two different tables have an exact match of data?

Example:

select count(distinct table1.col1)
  from table1
 where table1.col1 not in (select distinct table2.col1 
                             from table2);

This would return the number of values in table1.col1 that are not in table2. However, I don't know that this is a good solution as it doesn't count the table2.col1 values that do not exist in table1.col1.

like image 557
galford13x Avatar asked Apr 08 '10 19:04

galford13x


2 Answers

You can use two EXCEPT queries (or union them) to check:

SELECT DISTINCT col1
FROM table1
EXCEPT
SELECT DISTINCT col1
FROM table2

That will show values that exist in table1, but not table2. Then run again with table names flipped for the opposite.

like image 189
Chad Birch Avatar answered Oct 20 '22 00:10

Chad Birch


Use:

SELECT MAX(x.t1_missing_count) AS t1_missing_count, 
       MAX(x.t2_missing_count) AS t2_missing_count
  FROM (
SELECT COUNT(DISTINCT t1.col1) AS t1_missing_count,
       NULL AS t2_missing_count
  FROM TABLE_1 t1
 WHERE t1.col1 NOT IN (SELECT DISTINCT t2.col1 
                         FROM TABLE_2 t2)
UNION ALL
SELECT NULL,
       COUNT(DISTINCT t2.col1),           
  FROM TABLE_2 t2
 WHERE t2.col1 NOT IN (SELECT DISTINCT t1.col1 
                         FROM TABLE_1 t1)) x
like image 27
OMG Ponies Avatar answered Oct 20 '22 00:10

OMG Ponies