Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two columns for equality in SQL Server?

I have two columns that are joined together on certain criteria, but I would also like to check if two other columns are identical and then return a bit field if they are.

Is there a simpler solution than using CASE WHEN?

Ideally I could just use:

    SELECT Column1 = Column2 AS MyDesiredResult       FROM Table1 INNER JOIN Table2 ON Table1.PrimaryKey = Table2.ForeignKey 
like image 266
Orion Adrian Avatar asked Oct 27 '09 18:10

Orion Adrian


People also ask

How do I check if two values are equal in SQL?

In SQL, you can use the = operator to test for equality in a query. In this example, the SELECT statement above would return all rows from the suppliers table where the supplier_name is equal to Microsoft.

How do I compare two columns in the same table in SQL?

Comparison of columns in the same table is possible with the help of joins. Here we are comparing all the customers that are in the same city using the self join in SQL. Self-join is a regular join where a table is joined by itself. Similarly, a table may be joined with left join, right join, inner join, and full join.

How do you check for equal conditions in SQL query?

In SQL Server, you can use the = operator to test for equality in a query. WHERE first_name = 'Jane'; In this example, the SELECT statement above would return all rows from the employees table where the first_name is equal to Jane.

How can I compare more than two columns in SQL?

If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.


2 Answers

What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.

CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult 

should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.

like image 57
Ken White Avatar answered Sep 25 '22 10:09

Ken White


CASE WHEN is the better option

SELECT    CASE WHEN COLUMN1 = COLUMN2      THEN '1'      ELSE '0'    END    AS MyDesiredResult FROM Table1 INNER JOIN Table2 ON Table1.PrimaryKey = Table2.ForeignKey 
like image 27
MUHASIN BABU Avatar answered Sep 23 '22 10:09

MUHASIN BABU