Are there limits to the use of logical operators in the Mysql query?

Asked

Viewed 170 times

0

Well, I wonder if there are limits on how many logical operators I can use in a Mysql query, for example:

$sql = "SELECT * FROM usuarios WHERE nome = 'Fulano' OR email = '[email protected]' AND id <> '1'";

I would also like to know if this consultation above is valid.. Thank you!

2 answers

1


There are no operator limits, but they directly affect the performance of the query, including the order in which they are placed.

Your query is valid, but may not bring you the desired result by the order of the operators. The AND will always be processed before the OR, so the results returned by the query, has the name equal to 'Fulano' or the email equal to the informed and id different from 1.

To correct this problem, use parentheses to inform which will be processed first, this way:

$sql = "SELECT * FROM usuarios WHERE (nome = 'Fulano' OR email = '[email protected]') AND id <> 1";

If your field id is numeric, it is not required that it is in quotes ('1') the database will have to perform text to number conversion unnecessarily.

Still on the operators, in mathematical logic the operator AND corresponds to multiplication, and the OR to addition. Therefore of the order, only mathematics.

1

You can add as many operators as needed in your query, there are no limits, and you can improve conditions by isolating each one by placing them in parentheses.

Your example:

$sql = "SELECT * FROM usuarios WHERE nome = 'Fulano' OR email = '[email protected]' AND id <> '1'";

May not bring the desired result, the most convenient would be:

$sql = "SELECT * FROM usuarios WHERE (nome = 'Fulano') OR (email = '[email protected]') AND (id <> 1)";

Just as another result could be different (could, is not a statement):

$sql = "SELECT * FROM usuarios WHERE (nome = 'Fulano' OR email = '[email protected]') AND (id <> 1)";

The performance of your query may be better if you start at the least likely condition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.