Skip to Content
MySQL Stored Procedure Programming
book

MySQL Stored Procedure Programming

by Guy Harrison, Steven Feuerstein
March 2006
Intermediate to advanced
640 pages
17h 8m
English
O'Reilly Media, Inc.
Content preview from MySQL Stored Procedure Programming

IF and CASE Statements

Another category of statement that is highly amenable to code optimization is the conditional statement category—IF and CASE statements. This is especially true if these statements are called repetitively within a loop. The essence of optimizing conditional statements like IF and CASE is to reduce the number of comparisons that are performed. You can do this by:

  • Testing for the more likely matches earlier in the IF or CASE statement

  • Stopping the comparison process as early as possible

Test for the Most Likely Conditions First

When constructing IF and CASE statements, try to minimize the number of comparisons that these statements are likely to make by testing for the most likely scenarios first. For instance, consider the IF statement shown in Example 22-14. This statement maintains counts of various percentages. Assuming that the input data is evenly distributed, the first IF condition (percentage>95) will match about once in every 20 executions. On the other hand, the final condition will match in three out of four executions. So this means that for 75% of the cases, all four comparisons will need to be evaluated.

Example 22-14. Poorly constructed IF statement

        IF (percentage>95) THEN
             SET Above95=Above95+1;
        ELSEIF (percentage >=90) THEN
             SET Range90to95=Range90to95+1;
        ELSEIF (percentage >=75) THEN
             SET Range75to89=Range75to89+1;
        ELSE
             SET LessThan75=LessThan75+1;
        END IF;

Example 22-15 shows a more efficiently formed IF statement. In this variation, the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL and JSON: A Practical Programming Guide

MySQL and JSON: A Practical Programming Guide

David Stokes
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
Advanced MySQL 8

Advanced MySQL 8

Eric Vanier, Birju Shah, Tejaswi Malepati

Publisher Resources

ISBN: 0596100892Supplemental ContentErrata Page