Home > Back-end >  MySQL, <> clause and OR logic
MySQL, <> clause and OR logic

Time:12-19

Beginning SQL learner here. I have the following database 'drink_name' with drinks (taken from Head First SQL):

| Blackthorn       |
| Blue Moon        |
| Oh My Gosh       |
| Lime Fizz        |
| Kiss on the Lips |
| Hot Gold         |
| Lone Tree        |
| Greyhound        |
| Indian Summer    |
| Bull Frog        |
| Soda and It      |

This is the 'drink_name' column. Then I have another column with 'main' ingredients. Among them soda, iced water, etc etc.

I'm playing around and I came upon the following query:

SELECT drink_name FROM easy_drinks WHERE main <> 'soda' OR main <> 'iced tea';

And I'm trying to understand why this query returns EVERY entry. What's the logic behind this? I know if I wanted to have only the ones without those ingredients I can use AND, and then only the ones without soda or iced tea would come up, but this one I'm puzzled about. Thanks.

CodePudding user response:

This has not much to do with SQL, it's simple boolean logic: your condition is always true. The same way that x <> 1 OR x <> 0 is true for any number, main <> 'soda' OR main <> 'iced tea' will be true for any value of main.

Or maybe you didn't know that WHERE TRUE returns every entry in SQL?

CodePudding user response:

This query will return every entry because the conditions given in the where clause always return true. Let's illustrate this in details-- As the condition mentioned is main <> 'soda' it means the rows having the main not equal to soda are selected to the final entry and also the second condition main <> 'iced tea' means the rows having the main not equal to iced tea are selected to the final entry.As,both the conditions are connected with boolean logic 'Or' so it always returns the true.That's why it retrieves the all the records.

  • Related