0

I faced this question in an interview. They asked is there any hierarchy.
Ex: SELECT * FROM invoice WHERE invoiceID=100 AND grossAmount>2000 AND customerName= 'Adam'
Is there a special hierarchy to add those 3 conditions? Something Like check numeric condition first? Please give me your opinion.

Dil.
  • 1,996
  • 7
  • 41
  • 68

2 Answers2

2

The query optimizer will look at the conditions in the WHERE clause and evaluate them in whatever order it finds that:

  1. Ensures correctness
  2. Takes advantage of indexes and other information about the DB

For example, if you had an index on invoiceID it might evaluate that first so that it had fewer rows to examine in checking customerName and grossAmount.

Your example is all 'AND' clauses so there is no precedence involved.

n8wrl
  • 19,439
  • 4
  • 63
  • 103
  • Ok.. Thank you. So you are saying if I put indexing it will be easier to put a search order. Usually when I develop my database using mysql workbeanch I add indexing. Is there any way to put indexing within the where close? I know this is a stupid question, but is there? – Dil. Feb 26 '15 at 20:54
  • 1
    There is a way to force MySQL use certain indexes (only if they are present in database schema). Look up USE INDEX and FORCE INDEX. And yes, this is veeeery rarely a good idea. – Stanislav Shabalin Feb 26 '15 at 21:32
1

Here is the official documentation on Oracle's website

In your case, the query will run as its written since = and < have same operator precedence.

SELECT * FROM invoice WHERE (invoiceID=100 AND grossAmount>2000 AND customerName= 'Adam')

If it was an OR clause

 SELECT * FROM invoice WHERE (invoiceID=100) OR (grossAmount>2000 AND customerName= 'Adam')

Then the AND would run first and then OR. Only in cases where same operators exists then it gets to = + etc. Check documentation for order.

Polynomial Proton
  • 5,020
  • 20
  • 37