0

Please help with following if statement in MySQL 5.5. I am trying to compare column values to see if they are all equal or different.

SELECT IF(Column1 = Column2 = Column3 = Column4 = Column5, 'SAME', 'Different') 
AS ValueStatus 
FROM dbs.tabletest
GROUP BY Id

I have also tried the following, however, it only brings one type result as "Different" even when all columns have the same values.

  SELECT *,CASE 
  WHEN Column1 = Column2 = Column3 = Column4 = Column5 
    Then 'Same'
  ELSE 'Different' 
 END
  AS ValueStatus 
  FROM dbs.tabletest
  GROUP BY Id;

2 Answers 2

3

Should be column1 = column2 and column1 = column3 and column1 = column4 and column1 = column5 instead.

What happened to you is probably you compared column1 to column2, which returned true, then you compared true to column3, which yields false, compare false to column4, which also evaluates to false, etc.

9
  • Could you please further help on how to handle/ignore/filter out NULL values from these columns and only compare when NOT NULL, some columns have NULL values that change the status to different although all NOT NULL are Same values. Thanks Jan 26, 2012 at 18:23
  • Adding Col 1 or COL 2 or COL 3 'Is NOT NULL' in Where clause doesn't bring correct results. Where all Null values carrying columns are ignored, Have to track NULLS but want these to be ignored while comparing equality of only NON NULL COLUMNS Jan 26, 2012 at 18:47
  • Don't add it to your where clause. Either modify your IF statement or move to a CASE statement which may be a little bit easier to follow. Jan 26, 2012 at 18:59
  • just replace comparisons with something like IFNULL(column1=column2,TRUE) AND IFNULL(column1=column3,TRUE)... Jan 26, 2012 at 19:18
  • No luck so far with the following: Select *, IF(IFNULL( Col1 = Col2, TRUE) AND IFNULL(Col1 = Col3, TRUE) AND IFNULL( Col1= Col4, TRUE) AND IFNULL(Col1 = Col5,TRUE), 'Same', 'Different' ) AS ValueStatus From db.tablename Group by Id ; Tried COALESCE instead of IFNULL , no luck, first row has col 1, 2, 3 similar but col4 and 5 null bring valuestatus as Different, Second row has col1, null and all other similar value, brings valuestatus as Different again; Thinking of switching to CASE SELECT, ...will wait for response, though Jan 26, 2012 at 20:04
0

Michael's approch is right. i would use as following in MSSQL. not sure syntex in MySql. select Case WHEN ((column1 = column2) AND (column1 = column3) and (column1 = column4) and (column1 = column5) ) then 'Same' ELSE 'Different' end as 'ValueStatus' FROM tableName

1
  • Yes, I also prefer case (mysql has it as well), but the part of interest was condition. Jan 26, 2012 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.