1

I want to delete 2 distict rows, but with simular data. 3 colums, 1 is unique, and the other 2 are switched around. I was using something like this but it only delete 1.

DELETE FROM Table 
WHERE Column1 = 'a' AND Column2 = 'b' 
   OR column1 = 'b' AND Column2 = 'a'

This only deleted one column the statement. Thanks for any help

5
  • 2
    How should we know why this happens if you don't provide example data? Commented Sep 24, 2011 at 3:17
  • 1
    Show the sample data which should be deleted with this query Commented Sep 24, 2011 at 3:17
  • 3
    Also, add parenthesis to help clarify your meanings, AND and OR might not be working the way you think they are (Column1='a' and Column2='b') OR (column1='B' and Column2='a') Commented Sep 24, 2011 at 3:19
  • You mean "This only deleted one row" right? You SQL is correct, it should delete 2 rows if they really exist, unless you have a delete trigger that causes the second row to fail. Commented Sep 24, 2011 at 11:47
  • Did the best answer solved your problem? I doubt, because your query WHERE Column1 = 'a' AND Column2 = 'b' OR column1 = 'b' AND Column2 = 'a' is exactly the same as WHERE (Column1 = 'a' AND Column2 = 'b') OR (column1 = 'b' AND Column2 = 'a') as was proposed in the best answer. In other words, your query works fine the way you asked. Commented Sep 24, 2011 at 13:01

1 Answer 1

3

In SQL AND takes preference over OR.

Your where clause is interpreted as

WHERE (Column1 = 'a') 
  AND (Column2 = 'b' OR column1 = 'b') 
  AND (Column2 = 'a')

This is quite likely not what you want and you should (almost) always put the OR'ed tests in parenthesis like so:

WHERE (Column1 = 'a' AND Column2 = 'b') 
   OR (column1 = 'b' AND Column2 = 'a')

See: http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

Sign up to request clarification or add additional context in comments.

1 Comment

"In SQL AND takes preference over OR" - that's correct, but your explanation is wrong. In fact, his where clause is correct without parenthesis, as it is the same as (Column1 = 'a' AND Column2 = 'b') OR (column1 = 'b' AND Column2 = 'a')

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.