Search code examples
mysqlquery-optimizationcoldfusion-9

MySQL - Where clause processing order


This is a basic question. I inherited some code containing a cfquery. It runs on CF9 with MySQL 5.6. The cfquery reads:

SELECT some_columns 
FROM   tablename 
WHERE  itemname = 'itemnamevar' 
AND    id > 0 
ORDER BY orderby

The table contains more than 20000 items. ID is the primary key autoincrement value. It looks to me like the previous coder used to put id > 0 into the query to prepend some other clause conditions to the query. If none of them are used (controlled by some if/else), the id > 0 should cause all data from the table to be selected.

So the code is used as:

SELECT some_columns
FROM   tablename
WHERE 
<cfif id>
   id = '###'
<cfelse>
   <cfif LEN(itemname)>
      itemname = 'itemnamevar' AND 
   </cfif>
   <cfif LEN(itemgroup)>
      itemgroup = 'itemgroupvar' AND 
   </cfif>
   id > 0
</cfif>

My question is: if all the other clauses minimize the query set, before the id > 0 is processed, can I assume the id > 0 will have no effect on performance or should I rewrite the code to remove that condition? This will take some time because there are plenty of queries to optimize.

I need to say that the website running this code has some heavy load (more than 200k visitors a month growing relatively quick).

Thanks in advance. Please let me know if you need further information.


Solution

  • Use an expression that evaluates to TRUE without checking at the data. For example:

    1 = 1