5
\$\begingroup\$

I want to retrieve the row if any of the 3 integer field in a row is greater than zero. All the field has default value of zero.

Which of the following query is better?

-- Query 1
SELECT * FROM my_table WHERE number_A > 0 OR number_B > 0 OR number_C > 0
-- Query 2
SELECT * FROM my_table WHERE (number_A + number_B + number_C) > 0

While checking the execution time both the query gives same numbers and the result data of the query is exactly the same.

Toby Speight
87.1k14 gold badges104 silver badges322 bronze badges
asked Mar 19, 2017 at 6:50
\$\endgroup\$
2
  • 5
    \$\begingroup\$ Generating a query plan for each query will help you to decide. Otherwise, the first query is better in that the SGBD does not need to check the rest of the parameters if number_A satisfies the condition; while in the second query, the SGBD will have to check the values of the 3 parameters and sum them in all cases. \$\endgroup\$ Commented Mar 19, 2017 at 8:59
  • 1
    \$\begingroup\$ A 3rd way to write this (similar to Q1, but a bit shorter): WHERE (number_A, number_B, number_C) > (0, 0, 0) \$\endgroup\$ Commented Mar 19, 2017 at 11:35

2 Answers 2

4
\$\begingroup\$

In addition to the other differences between the two statements

WHERE (number_A + number_B + number_C) > 0

Could cause you problems if any of those three are negative. That may not be relevant in your case, but if one of these is negative the total might fail to exceed zero even if another of the values does exceed zero.

Stephen Rauch
4,31412 gold badges24 silver badges36 bronze badges
answered Apr 2, 2017 at 16:03
\$\endgroup\$
0
0
\$\begingroup\$

A good thing to do would be to use EXPLAIN on both of these statements to see how MySQL executes each of them. They may match identically. The reason for this is that SQL is a declarative programming language, meaning that your query is meant to express the logic of a computation, not it's control. MySQL then takes your query and it's optimizer determines the best / most efficient means of returning the results as defined by your query. Therefore, it can interpret your queries as identical, and execute them as such.

answered Mar 20, 2017 at 15:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.