I would like to perform a SELECT
query with MySQL. My goal is to select all the dogs in a vet database that would be sex=male
and fur=short
and (color=black or size=big
)
Note: I want to select dogs that are either black or size is big. They don't have to fulfill the 2 requirements. They just need to fulfill either one.
I have written the SQL statement below but I'm not not sure if I'm right:
SELECT name, sex, fur, color
FROM dogs
WHERE TRUE sex='male' AND fur='short' AND color='black' OR size="big";
Pardon my phrasing if it's too confusing.
SQL AND, OR and NOT OperatorsThe WHERE clause can be combined with AND , OR , and NOT operators. The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE.
You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
The SQL AND condition and OR condition can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement. When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.
The SQL Server (Transact-SQL) AND condition and OR condition can be combined in a SELECT, INSERT, UPDATE, or DELETE statement. When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.
According to Operator precedence for MySQL AND
has higher precedence than OR
.
So
C1 AND C2 OR C3
will be treated as (C1 AND C2) OR C3
To override the default precedence you need to use parenthesis as:C1 AND (C2 OR C3)
In your case the right query is:
SELECT name, sex, fur, color
FROM dogs
WHERE sex='male' AND fur='short' AND (color='black' OR size="big");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With