Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of rows which do not match

Tags:

sql

sql-server

I have two tables with exactly the same structure i.e. same columns. I want to find out number of rows which exist in both tables but do not have exactly the same matching values for all columns. E.g. Table has colums Id, Name, Country. Id is the primary key. If Id=1 exists in both tables then other values should also match. Currently, I am using this kind of statement.

SELECT  COUNT(*)
FROM    ##Table1 t1 ,
        ##Table2 t2
WHERE   t1.Id = t2.Id
        AND ( t1.Name != t2.name
              OR t1.Country != t2.Country
            )  

Table has too many columns hence this is becoming too unwieldly. Is there a better way to do it?

like image 471
user2761667 Avatar asked Sep 09 '13 14:09

user2761667


People also ask

What does COUNT (*) return if there are no rows?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

Which is used to COUNT number of rows?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.

Does COUNT () ignores NULL?

COUNT(expression) returns the number of values in expression, which is a table column name or an expression that evaluates to a column of data. COUNT(expression) does not count NULL values. This query returns the number of non-NULL values in the Name column of Sample.


1 Answers

SELECT COUNT(*)
FROM   ##Table1 t1
       JOIN ##Table2 t2
         ON t1.Id = t2.Id
            AND EXISTS (SELECT t1.*
                        EXCEPT
                        SELECT t2.*) 

SQL Fiddle

like image 108
Martin Smith Avatar answered Nov 15 '22 04:11

Martin Smith