Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select Statement with WHERE, AND, OR

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.

like image 482
dave Avatar asked Aug 27 '10 06:08

dave


People also ask

Can we use OR in WHERE clause in SQL?

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.

Can you use a SELECT statement in a WHERE clause?

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.

How do you write AND OR condition in SQL?

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.

Can we use AND in SELECT statement in SQL?

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.


1 Answers

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");
like image 171
codaddict Avatar answered Oct 24 '22 17:10

codaddict