Cover image for MySQL Stored Procedure Programming

Book description

The implementation of stored procedures in MySQL 5.0 a huge milestone -- one that is expected to lead to widespread enterprise adoption of the already extremely popular MySQL database. If you are serious about building the web-based database applications of the future, you need to get up to speed quickly on how stored procedures work -- and how to build them the right way. This book, destined to be the bible of stored procedure development, is a resource that no real MySQL programmer can afford to do without.

In the decade since MySQL burst on the scene, it has become the dominant open source database, with capabilities and performance rivaling those of commercial RDBMS offerings like Oracle and SQL Server. Along with Linux and PHP, MySQL is at the heart of millions of applications. And now, with support for stored procedures, functions, and triggers in MySQL 5.0, MySQL offers the programming power needed for true enterprise use.

MySQL's new procedural language has a straightforward syntax, making it easy to write simple programs. But it's not so easy to write secure, easily maintained, high-performance, and bug-free programs. Few in the MySQL world have substantial experience yet with stored procedures, but Guy Harrison and Steven Feuerstein have decades of combined expertise.

  • MySQL stored programming fundamentals -- tutorial, basic statements, SQL in stored programs, and error handling

  • Building MySQL stored programs -- transaction handling, built-in functions, stored functions, and triggers

  • MySQL stored programs in applications -- using stored programs with PHP, Java, Perl, Python, and .NET (C# and VB.NET)

  • Optimizing MySQL stored programs -- security, basic and advanced SQL tuning, optimizing stored program code, and programming best practices

A companion web site contains many thousands of lines of code, that you can put to use immediately.

Guy Harrison is Chief Architect of Database Solutions at Quest Software and a frequent speaker and writer on MySQL topics. Steven Feuerstein is the author of Oracle PL/SQL Programming, the classic reference for Oracle stored programming for more than ten years. Both have decades of experience as database developers, and between them they have authored a dozen books.

In MySQL Stored Procedure Programming, they put that hard-won experience to good use. Packed with code examples and covering everything from language basics to application building to advanced tuning and best practices, this highly readable book is the one-stop guide to MySQL development. It consists of four major sections:

Table of Contents

  1. MySQL Stored Procedure Programming
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Advance Praise for MySQL Stored Procedure Programming
    4. Preface
      1. Objectives of This Book
      2. Structure of This Book
      3. What This Book Does Not Cover
      4. Conventions Used in This Book
      5. Which Version?
      6. Resources Available at the Book's Web Site
      7. Using Code Examples
      8. Safari® Enabled
      9. How to Contact Us
      10. Acknowledgments
    5. I. Stored Programming Fundamentals
      1. 1. Introduction to MySQL Stored Programs
        1. 1.1. What Is a Stored Program?
          1. 1.1.1. Why Use Stored Programs?
          2. 1.1.2. A Brief History of MySQL
          3. 1.1.3. MySQL Stored Procedures, Functions, and Triggers
        2. 1.2. A Quick Tour
          1. 1.2.1. Integration with SQL
          2. 1.2.2. Control and Conditional Logic
          3. 1.2.3. Stored Functions
          4. 1.2.4. When Things Go Wrong
          5. 1.2.5. Triggers
        3. 1.3. Resources for Developers Using Stored Programs
          1. 1.3.1. Books
          2. 1.3.2. Internet Resources
        4. 1.4. Some Words of Advice for Developers
          1. 1.4.1. Don't Be in Such a Hurry!
          2. 1.4.2. Don't Be Afraid to Ask for Help
          3. 1.4.3. Take a Creative, Even Radical Approach
        5. 1.5. Conclusion
      2. 2. MySQL Stored Programming Tutorial
        1. 2.1. What You Will Need
        2. 2.2. Our First Stored Procedure
          1. 2.2.1. Creating the Procedure
          2. 2.2.2. Creating the Procedure Using the MySQL Query Browser
        3. 2.3. Variables
        4. 2.4. Parameters
          1. 2.4.1. Parameter Modes
        5. 2.5. Conditional Execution
        6. 2.6. Loops
        7. 2.7. Dealing with Errors
        8. 2.8. Interacting with the Database
          1. 2.8.1. SELECTing INTO Local Variables
          2. 2.8.2. Using Cursors
          3. 2.8.3. Returning Result Sets from Stored Procedures
          4. 2.8.4. Embedding Non-SELECTs
        9. 2.9. Calling Stored Programs from Stored Programs
        10. 2.10. Putting It All Together
        11. 2.11. Stored Functions
        12. 2.12. Triggers
        13. 2.13. Calling a Stored Procedure from PHP
        14. 2.14. Conclusion
      3. 3. Language Fundamentals
        1. 3.1. Variables, Literals, Parameters, and Comments
          1. 3.1.1. Variables
          2. 3.1.2. Literals
          3. 3.1.3. Rules for Variable Names
          4. 3.1.4. Assigning Values to Variables
          5. 3.1.5. Parameters
          6. 3.1.6. User Variables
          7. 3.1.7. Comments
        2. 3.2. Operators
          1. 3.2.1. Mathematical Operators
          2. 3.2.2. Comparison Operators
          3. 3.2.3. Logical Operators
          4. 3.2.4. Bitwise Operators
        3. 3.3. Expressions
        4. 3.4. Built-in Functions
        5. 3.5. Data Types
          1. 3.5.1. String Data Types
            1. 3.5.1.1. The ENUM data type
            2. 3.5.1.2. The SET data type
          2. 3.5.2. Numeric Data Types
          3. 3.5.3. Date and Time Data Types
          4. 3.5.4. TEXT and BLOB Data Types
        6. 3.6. MySQL 5 "Strict" Mode
          1. 3.6.1. Stored Program Behavior and Strict Mode
          2. 3.6.2. Program Examples
        7. 3.7. Conclusion
      4. 4. Blocks, Conditional Statements, and Iterative Programming
        1. 4.1. Block Structure of Stored Programs
          1. 4.1.1. Structure of a Block
          2. 4.1.2. Nested Blocks
        2. 4.2. Conditional Control
          1. 4.2.1. The IF Statement
            1. 4.2.1.1. TRUE or FALSE (or neither)?
            2. 4.2.1.2. Simple IF-THEN combinations
            3. 4.2.1.3. IF-THEN-ELSE statements
            4. 4.2.1.4. IF-THEN-ELSEIF-ELSE statements
          2. 4.2.2. The CASE Statement
            1. 4.2.2.1. Simple CASE statement
            2. 4.2.2.2. "Searched" CASE statement
          3. 4.2.3. IF Versus CASE
        3. 4.3. Iterative Processing with Loops
          1. 4.3.1. LOOP Statement
          2. 4.3.2. LEAVE Statement
          3. 4.3.3. ITERATE Statement
          4. 4.3.4. REPEAT ... UNTIL Loop
          5. 4.3.5. WHILE Loop
          6. 4.3.6. Nested Loops
          7. 4.3.7. Parting Comments on Loops
        4. 4.4. Conclusion
      5. 5. Using SQL in Stored Programming
        1. 5.1. Using Non-SELECT SQL in Stored Programs
        2. 5.2. Using SELECT Statements with an INTO Clause
        3. 5.3. Creating and Using Cursors
          1. 5.3.1. Defining a Cursor
          2. 5.3.2. Cursor Statements
          3. 5.3.3. Fetching a Single Row from a Cursor
          4. 5.3.4. Fetching an Entire Result Set
          5. 5.3.5. Types of Cursor Loops
          6. 5.3.6. Nested Cursor Loops
          7. 5.3.7. Exiting the Cursor Loop Prematurely
          8. 5.3.8. Cursor Error Conditions
        4. 5.4. Using Unbounded SELECT Statements
          1. 5.4.1. Retrieving the Result Sets in the Calling Program
          2. 5.4.2. Returning Result Sets to Another Stored Procedure
        5. 5.5. Performing Dynamic SQL with Prepared Statements
        6. 5.6. Handling SQL Errors: A Preview
        7. 5.7. Conclusion
      6. 6. Error Handling
        1. 6.1. Introduction to Error Handling
          1. 6.1.1. A Simple First Example
          2. 6.1.2. Handling Last Row Conditions
        2. 6.2. Condition Handlers
          1. 6.2.1. Types of Handlers
          2. 6.2.2. Handler Conditions
          3. 6.2.3. Handler Examples
          4. 6.2.4. Handler Precedence
          5. 6.2.5. Scope of Condition Handlers
        3. 6.3. Named Conditions
        4. 6.4. Missing SQL:2003 Features
          1. 6.4.1. Directly Accessing SQLCODE or SQLSTATE
          2. 6.4.2. Creating Your Own Exceptions with the SIGNAL Statement
          3. 6.4.3. Emulating the SIGNAL Statement
        5. 6.5. Putting It All Together
        6. 6.6. Handling Stored Program Errors in the Calling Application
          1. 6.6.1. PHP
          2. 6.6.2. Perl
          3. 6.6.3. Java/JDBC
          4. 6.6.4. Python
          5. 6.6.5. C# .NET
          6. 6.6.6. Visual Basic .NET
        7. 6.7. Conclusion
    6. II. Stored Program Construction
      1. 7. Creating and Maintaining Stored Programs
        1. 7.1. Creating Stored Programs
          1. 7.1.1. Editing Stored Programs Using a System Editor
          2. 7.1.2. Using the MySQL Query Browser
          3. 7.1.3. Using Third-Party Tools
          4. 7.1.4. Handling Semicolons in Stored Program Code
        2. 7.2. Editing an Existing Stored Program
          1. 7.2.1. Editing a Program in Place
          2. 7.2.2. Maintaining Stored Programs in External Files
        3. 7.3. SQL Statements for Managing Stored Programs
          1. 7.3.1. CREATE PROCEDURE
          2. 7.3.2. CREATE FUNCTION
          3. 7.3.3. CREATE TRIGGER
          4. 7.3.4. ALTER PROCEDURE/FUNCTION
          5. 7.3.5. DROP PROCEDURE/FUNCTION/TRIGGER
        4. 7.4. Getting Information About Stored Programs
          1. 7.4.1. SHOW PROCEDURE/FUNCTION STATUS
          2. 7.4.2. SHOW CREATE PROCEDURE/FUNCTION
          3. 7.4.3. INFORMATION_SCHEMA.ROUTINES Table
          4. 7.4.4. INFORMATION_SCHEMA.TRIGGERS Table
        5. 7.5. Conclusion
      2. 8. Transaction Management
        1. 8.1. Transactional Support in MySQL
          1. 8.1.1. Isolation Levels
          2. 8.1.2. Transaction Management Statements
        2. 8.2. Defining a Transaction
        3. 8.3. Working with Savepoints
        4. 8.4. Transactions and Locks
          1. 8.4.1. Situations in Which Locks Arise
          2. 8.4.2. Deadlocks
          3. 8.4.3. Lock Timeouts
          4. 8.4.4. Optimistic and Pessimistic Locking Strategies
            1. 8.4.4.1. Pessimistic locking strategy
            2. 8.4.4.2. Optimistic locking strategy
            3. 8.4.4.3. Choosing between strategies
        5. 8.5. Transaction Design Guidelines
        6. 8.6. Conclusion
      3. 9. MySQL Built-in Functions
        1. 9.1. String Functions
          1. 9.1.1. ASCII
          2. 9.1.2. CHAR
          3. 9.1.3. CHARSET
          4. 9.1.4. CONCAT
          5. 9.1.5. CONCAT_WS
          6. 9.1.6. INSERT
          7. 9.1.7. INSTR
          8. 9.1.8. LCASE
          9. 9.1.9. LEFT
          10. 9.1.10. LENGTH
          11. 9.1.11. LOAD_FILE
          12. 9.1.12. LOCATE
          13. 9.1.13. LPAD
          14. 9.1.14. LTRIM
          15. 9.1.15. REPEAT
          16. 9.1.16. REPLACE
          17. 9.1.17. RPAD
          18. 9.1.18. RTRIM
          19. 9.1.19. STRCMP
          20. 9.1.20. SUBSTRING
          21. 9.1.21. TRIM
          22. 9.1.22. UCASE
          23. 9.1.23. Other String Functions
        2. 9.2. Numeric Functions
          1. 9.2.1. ABS
          2. 9.2.2. BIN
          3. 9.2.3. CEILING
          4. 9.2.4. CONV
          5. 9.2.5. FLOOR
          6. 9.2.6. FORMAT
          7. 9.2.7. HEX
          8. 9.2.8. LEAST
          9. 9.2.9. MOD
          10. 9.2.10. POWER
          11. 9.2.11. RAND
          12. 9.2.12. ROUND
          13. 9.2.13. SIGN
          14. 9.2.14. SQRT
          15. 9.2.15. Other Numeric Functions
        3. 9.3. Date and Time Functions
          1. 9.3.1. ADDTIME
          2. 9.3.2. CONVERT_TZ
          3. 9.3.3. CURRENT_DATE
          4. 9.3.4. CURRENT_TIME
          5. 9.3.5. CURRENT_TIMESTAMP
          6. 9.3.6. DATE
          7. 9.3.7. DATE_ADD
          8. 9.3.8. DATE_FORMAT
          9. 9.3.9. DATE_SUB
          10. 9.3.10. DATEDIFF
          11. 9.3.11. DAY
          12. 9.3.12. DAYNAME
          13. 9.3.13. DAYOFWEEK
          14. 9.3.14. DAYOFYEAR
          15. 9.3.15. EXTRACT
          16. 9.3.16. GET_FORMAT
          17. 9.3.17. MAKEDATE
          18. 9.3.18. MAKETIME
          19. 9.3.19. MONTHNAME
          20. 9.3.20. NOW
          21. 9.3.21. SEC_TO_TIME
          22. 9.3.22. STR_TO_DATE
          23. 9.3.23. TIME_TO_SEC
          24. 9.3.24. TIMEDIFF
          25. 9.3.25. TIMESTAMP
          26. 9.3.26. TIMESTAMPADD
          27. 9.3.27. TIMESTAMPDIFF
          28. 9.3.28. WEEK
          29. 9.3.29. WEEKDAY
          30. 9.3.30. YEAR
          31. 9.3.31. YEARWEEK
          32. 9.3.32. Other Date and Time Functions
        4. 9.4. Other Functions
          1. 9.4.1. BENCHMARK
          2. 9.4.2. COALESCE
          3. 9.4.3. CURRENT_USER
          4. 9.4.4. DATABASE
          5. 9.4.5. GET_LOCK
          6. 9.4.6. IFNULL
          7. 9.4.7. INTERVAL
          8. 9.4.8. IS_FREE_LOCK
          9. 9.4.9. ISNULL
          10. 9.4.10. NULLIF
          11. 9.4.11. RELEASE_LOCK
          12. 9.4.12. SESSION_USER
          13. 9.4.13. SYSTEM_USER
          14. 9.4.14. USER
          15. 9.4.15. UUID
          16. 9.4.16. VERSION
        5. 9.5. Conclusion
      4. 10. Stored Functions
        1. 10.1. Creating Stored Functions
          1. 10.1.1. The RETURN Statement
          2. 10.1.2. Parameters to Stored Functions
          3. 10.1.3. The DETERMINISTIC and SQL Clauses
        2. 10.2. SQL Statements in Stored Functions
        3. 10.3. Calling Stored Functions
        4. 10.4. Using Stored Functions in SQL
          1. 10.4.1. Using SQL in Stored Functions
        5. 10.5. Conclusion
      5. 11. Triggers
        1. 11.1. Creating Triggers
          1. 11.1.1. Referring to Column Values Within the Trigger
          2. 11.1.2. Triggering Actions
          3. 11.1.3. BEFORE and AFTER Triggers
        2. 11.2. Using Triggers
          1. 11.2.1. Maintaining Derived Data
          2. 11.2.2. Implementing Logging
          3. 11.2.3. Validating Data with Triggers
        3. 11.3. Trigger Overhead
        4. 11.4. Conclusion
    7. III. Using MySQL Stored Programs in Applications
      1. 12. Using MySQL Stored Programs in Applications
        1. 12.1. The Pros and Cons of Stored Programs in Modern Applications
        2. 12.2. Advantages of Stored Programs
          1. 12.2.1. They Enhance Database Security
          2. 12.2.2. They Provide a Mechanism for Data Abstraction
          3. 12.2.3. They Reduce Network Traffic
          4. 12.2.4. They Allow for Common Routines Across Multiple Application Types
          5. 12.2.5. They Facilitate Division of Duties
          6. 12.2.6. They May Provide Portability
        3. 12.3. Disadvantages of Stored Programs
          1. 12.3.1. They Can Be Computationally Inferior
          2. 12.3.2. They Can Lead to Logic Fragmentation
          3. 12.3.3. They Do Not Provide Portability
        4. 12.4. Calling Stored Programs from Application Code
          1. 12.4.1. Preparing a Stored Program Call for Execution
          2. 12.4.2. Registering Parameters
          3. 12.4.3. Setting Output Parameters
          4. 12.4.4. Executing the Stored Program
          5. 12.4.5. Retrieving Result Sets
          6. 12.4.6. Retrieving Output Parameters
          7. 12.4.7. Closing or Re-Executing the Stored Program
          8. 12.4.8. Calling Stored Functions
        5. 12.5. Conclusion
      2. 13. Using MySQL Stored Programs with PHP
        1. 13.1. Options for Using MySQL with PHP
        2. 13.2. Using PHP with the mysqli Extension
          1. 13.2.1. Enabling the mysqli Extension
          2. 13.2.2. Connecting to MySQL
          3. 13.2.3. Checking for Errors
          4. 13.2.4. Executing a Simple Non-SELECT Statement
          5. 13.2.5. Retrieving a Result Set
          6. 13.2.6. Managing Transactions
          7. 13.2.7. Using Prepared Statements
          8. 13.2.8. Retrieving Result Sets from Prepared Statements
          9. 13.2.9. Getting Result Set Metadata
          10. 13.2.10. Processing a Dynamic Result Set
          11. 13.2.11. Calling Stored Programs with mysqli
          12. 13.2.12. Handling Output Parameters
          13. 13.2.13. Retrieving Multiple Result Sets
        3. 13.3. Using MySQL with PHP Data Objects
          1. 13.3.1. Connecting to MySQL
          2. 13.3.2. Executing a Simple Non-SELECT Statement
          3. 13.3.3. Catching Errors
          4. 13.3.4. Managing Transactions
          5. 13.3.5. Issuing a One-Off Query
          6. 13.3.6. Using Prepared Statements
          7. 13.3.7. Binding Parameters to a Prepared Statement
          8. 13.3.8. Getting Result Set Metadata
          9. 13.3.9. Processing a Dynamic Result Set
          10. 13.3.10. Calling Stored Programs with PDO
          11. 13.3.11. Binding Input Parameters to Stored Programs
          12. 13.3.12. Handling Multiple Result Sets
          13. 13.3.13. Handling Output Parameters
          14. 13.3.14. A Complete Example
        4. 13.4. Conclusion
      3. 14. Using MySQL Stored Programs with Java
        1. 14.1. Review of JDBC Basics
          1. 14.1.1. Installing the Driver and Configuring Your IDE
          2. 14.1.2. Registering the Driver and Connecting to MySQL
          3. 14.1.3. Issuing a Non-SELECT Statement
          4. 14.1.4. Issuing a SELECT and Retrieving a Result Set
          5. 14.1.5. Getting Result Set Metadata
          6. 14.1.6. Using Prepared Statements
          7. 14.1.7. Handling Transactions
          8. 14.1.8. Handling Errors
        2. 14.2. Using Stored Programs in JDBC
          1. 14.2.1. Using the CallableStatement Interface
          2. 14.2.2. Registering OUT Variables
          3. 14.2.3. Supplying Input Parameters
          4. 14.2.4. Executing the Procedure
          5. 14.2.5. Retrieving a Result Set
          6. 14.2.6. Retrieving Multiple Result Sets
          7. 14.2.7. Dynamically Processing Result Sets
          8. 14.2.8. Retrieving Output Parameter Values
        3. 14.3. Stored Programs and J2EE Applications
          1. 14.3.1. Using Stored Programs Within Java Servlets
          2. 14.3.2. Using Stored Programs from EJB
        4. 14.4. Using Stored Procedures with Hibernate
          1. 14.4.1. Hibernate Support for MySQL Stored Procedures
          2. 14.4.2. Using a Stored Procedure to Load an Object
          3. 14.4.3. Hibernate Queries
          4. 14.4.4. Using Stored Procedures for Persistence
        5. 14.5. Using Stored Procedures with Spring
        6. 14.6. Conclusion
      4. 15. Using MySQL Stored Programs with Perl
        1. 15.1. Review of Perl DBD::mysql Basics
          1. 15.1.1. Installing DBD::mysql
            1. 15.1.1.1. Installing DBD::mysql on Linux or Unix
            2. 15.1.1.2. Installing DBD::mysql on Windows
          2. 15.1.2. Connecting to MySQL
            1. 15.1.2.1. Connection attributes
          3. 15.1.3. Handling Errors
          4. 15.1.4. Issuing a Simple One-off Statement
          5. 15.1.5. Preparing a Statement for Reuse
          6. 15.1.6. Using Bind Variables
          7. 15.1.7. Issuing a Query and Retrieving Results
          8. 15.1.8. There's More Than One Way To Do It
            1. 15.1.8.1. fetchrow_arrayref method
            2. 15.1.8.2. fetchrow_hashref method
            3. 15.1.8.3. fetchall_arrayref method
            4. 15.1.8.4. dump_results method
            5. 15.1.8.5. bind_col and fetch methods
          9. 15.1.9. Getting Result Set Metadata
          10. 15.1.10. Performing Transaction Management
        2. 15.2. Executing Stored Programs with DBD::mysql
          1. 15.2.1. Handling Multiple Result Sets
          2. 15.2.2. Handling Dynamic Result Sets
          3. 15.2.3. Handling Output Variables
          4. 15.2.4. A Complete Example
        3. 15.3. Conclusion
      5. 16. Using MySQL Stored Programs with Python
        1. 16.1. Installing the MySQLdb Extension
        2. 16.2. MySQLdb Basics
          1. 16.2.1. Creating a Connection
          2. 16.2.2. Handling Exceptions
          3. 16.2.3. Executing a Simple Statement
          4. 16.2.4. Passing Parameters to a Statement
          5. 16.2.5. Retrieving Rows from a Query
          6. 16.2.6. Managing Transactions
          7. 16.2.7. Getting Metadata
          8. 16.2.8. Dynamically Processing a Result Set
        3. 16.3. Using Stored Programs with MySQLdb
          1. 16.3.1. Calling Simple Stored Programs
          2. 16.3.2. Retrieving a Single Stored Program Result Set
          3. 16.3.3. Retrieving Multiple Stored Program Result Sets
          4. 16.3.4. Retrieving Dynamic Result Sets
          5. 16.3.5. Obtaining Output Parameters
        4. 16.4. A Complete Example
        5. 16.5. Conclusion
      6. 17. Using MySQL Stored Programs with .NET
        1. 17.1. Review of ADO.NET Basics
          1. 17.1.1. Installing the Connector/Net Driver and Configuring Your IDE
          2. 17.1.2. Registering the Driver and Connecting to MySQL
          3. 17.1.3. Issuing a Non-SELECT Statement
          4. 17.1.4. Reusing a Statement Object
          5. 17.1.5. Using Parameters
          6. 17.1.6. Issuing a SELECT and Using a DataReader
          7. 17.1.7. Getting DataReader Metadata
          8. 17.1.8. DataSets
          9. 17.1.9. Handling Errors
          10. 17.1.10. Managing Transactions
        2. 17.2. Using Stored Programs in ADO.NET
          1. 17.2.1. Calling a Simple Stored Procedure
          2. 17.2.2. Supplying Input Parameters
          3. 17.2.3. Using a DataReader with a Stored Program
          4. 17.2.4. Processing Multiple Result Sets in a DataReader
          5. 17.2.5. Dynamically Processing Result Sets
          6. 17.2.6. Using DataSets with Stored Programs
          7. 17.2.7. Retrieving Output Parameters
          8. 17.2.8. Calling Stored Functions
        3. 17.3. Using Stored Programs in ASP.NET
        4. 17.4. Conclusion
    8. IV. Optimizing Stored Programs
      1. 18. Stored Program Security
        1. 18.1. Permissions Required for Stored Programs
          1. 18.1.1. Granting Privileges to Create a Stored Program
          2. 18.1.2. Granting Privileges to Modify a Stored Program
          3. 18.1.3. Granting Privileges to Execute a Stored Program
        2. 18.2. Execution Mode Options for Stored Programs
          1. 18.2.1. The SQL SECURITY Clause
          2. 18.2.2. Using Definer Rights to Implement Security Policies
          3. 18.2.3. Stored Program or View?
          4. 18.2.4. Handling Invoker Rights Errors
        3. 18.3. Stored Programs and Code Injection
          1. 18.3.1. Protecting Against SQL Injection with Stored Programs
          2. 18.3.2. SQL Injection in Stored Programs
        4. 18.4. Conclusion
      2. 19. Tuning Stored Programs and Their SQL
        1. 19.1. Why SQL Tuning Is So Important
          1. 19.1.1. An Instructive Example
        2. 19.2. How MySQL Processes SQL
          1. 19.2.1. Parsing SQL
          2. 19.2.2. Caching
            1. 19.2.2.1. Buffer pool and key cache
            2. 19.2.2.2. Table cache
            3. 19.2.2.3. Query cache
            4. 19.2.2.4. Table statistics
        3. 19.3. SQL Tuning Statements and Practices
          1. 19.3.1. EXPLAIN Statement
          2. 19.3.2. EXPLAIN and Stored Programs
          3. 19.3.3. Details of the EXPLAIN Output
          4. 19.3.4. Extended EXPLAIN
          5. 19.3.5. Optimizer Hints
          6. 19.3.6. Measuring SQL and Stored Program Execution
          7. 19.3.7. The Slow Query Log
        4. 19.4. About the Upcoming Examples
        5. 19.5. Conclusion
      3. 20. Basic SQL Tuning
        1. 20.1. Tuning Table Access
          1. 20.1.1. Index Lookup Versus Full Table Scan
          2. 20.1.2. How MySQL Chooses Between Indexes
          3. 20.1.3. Manually Choosing an Index
          4. 20.1.4. Prefixed ("Partial") Indexes
          5. 20.1.5. Concatenated Indexes
            1. 20.1.5.1. Merging multiple indexes
            2. 20.1.5.2. Covering indexes
          6. 20.1.6. Comparing the Different Indexing Approaches
          7. 20.1.7. Avoiding Accidental Table Scans
            1. 20.1.7.1. Accidentally suppressing an index using a function
            2. 20.1.7.2. Accidentally suppressing an index using a substring
            3. 20.1.7.3. Creating concatenated indexes with a poor column order
          8. 20.1.8. Optimizing Necessary Table Scans
          9. 20.1.9. Using Merge or Partitioned Tables
        2. 20.2. Tuning Joins
          1. 20.2.1. How MySQL Joins Tables
          2. 20.2.2. Joins Without Indexes
          3. 20.2.3. Joins with Indexes
          4. 20.2.4. Join Order
          5. 20.2.5. A Simple Join Example
        3. 20.3. Conclusion
      4. 21. Advanced SQL Tuning
        1. 21.1. Tuning Subqueries
          1. 21.1.1. Optimizing Subqueries
          2. 21.1.2. Rewriting a Subquery as a Join
          3. 21.1.3. Using Subqueries in Complex Joins
        2. 21.2. Tuning "Anti-Joins" Using Subqueries
          1. 21.2.1. Optimizing an Anti-Join
        3. 21.3. Tuning Subqueries in the FROM Clause
          1. 21.3.1. Using Views
        4. 21.4. Tuning ORDER and GROUP BY
          1. 21.4.1. Creating an Index to Avoid a Sort
          2. 21.4.2. Reducing Sort Overhead by Increasing Sort Memory
        5. 21.5. Tuning DML (INSERT, UPDATE, DELETE)
          1. 21.5.1. Batching Inserts
          2. 21.5.2. Optimizing DML by Reducing Commit Frequency
          3. 21.5.3. Triggers and DML Performance
        6. 21.6. Conclusion
      5. 22. Optimizing Stored Program Code
        1. 22.1. Performance Characteristics of Stored Programs
        2. 22.2. How Fast Is the Stored Program Language?
        3. 22.3. Reducing Network Traffic with Stored Programs
        4. 22.4. Stored Programs as an Alternative to Expensive SQL
          1. 22.4.1. Avoid Self-Joins with Procedural Logic
          2. 22.4.2. Optimize Correlated Updates
        5. 22.5. Optimizing Loops
          1. 22.5.1. Move Unnecessary Statements Out of a Loop
          2. 22.5.2. Use LEAVE or CONTINUE to Avoid Needless Processing
        6. 22.6. IF and CASE Statements
          1. 22.6.1. Test for the Most Likely Conditions First
          2. 22.6.2. Avoid Unnecessary Comparisons
          3. 22.6.3. CASE Versus IF
        7. 22.7. Recursion
        8. 22.8. Cursors
        9. 22.9. Trigger Overhead
        10. 22.10. Conclusion
      6. 23. Best Practices in MySQL Stored Program Development
        1. 23.1. The Development Process
          1. DEV-01: Set standards and guidelines before writing any code
          2. DEV-02: Ask for help after 30 minutes on a problem
          3. DEV-03: Walk through each other's code
          4. DEV-04: Use independent testers for functional sign-off
          5. DEV-05: Use source controlled files to maintain the "reference" copy of your stored routines
        2. 23.2. Coding Style and Conventions
          1. STYL-01: Adopt a consistent, readable format that is easy to maintain
          2. STYL-02: Adopt logical, consistent naming conventions for modules and data structures
          3. STYL-03: Self-document using block and loop labels
          4. STYL-04: Express complex expressions unambiguously using parentheses
          5. STYL-05: Use vertical code alignment to emphasize vertical relationships
          6. STYL-06: Comment tersely with value-added information
        3. 23.3. Variables
          1. DAT-01: Use a consistent and meaningful variable naming style
          2. DAT-02: Avoid overriding variable declarations within "inner" blocks
          3. DAT-03: Replace complex expressions with functions
          4. DAT-04: Remove unused variables and code
          5. DAT-05: Don't assume that the result of an expression is TRUE or FALSE; it could be NULL
          6. DAT-06: Employ "user" variables for global data sparingly
          7. DAT-07: Create stored programs in strict mode to avoid invalid data assignments
        4. 23.4. Conditional Logic
          1. IF-01: Use ELSEIF with mutually exclusive clauses
          2. IF-02: Use IF...ELSEIF only to test a single, simple condition
          3. IF-03: Make sure that a CASE statement is inclusive , or construct a handler to catch any unmatched cases
          4. IF-04: Use CASE and IF consistently
        5. 23.5. Loop Processing
          1. LOOP-01: Make sure the loop will terminate
          2. LOOP-02: Make the termination conditions of a loop obvious
          3. LOOP-03: Use a single LEAVE in simple loops
          4. LOOP-04: Use a simple loop to avoid redundant code required by a WHILE or REPEAT UNTIL loop
        6. 23.6. Exception Handling
          1. EXC-01: Handle exceptions that cannot be avoided but can be anticipated
          2. EXC-02: Use named conditions to improve code readability
          3. EXC-03: Be consistent in your use of SQLSTATE and MySQL error codes in exception handlers
          4. EXC-04: Avoid global SQLEXCEPTION handlers until MySQL implements SIGNAL and SQLCODE features
        7. 23.7. SQL in Stored Programs
          1. SQL-01: Start a transaction explicitly with the START TRANSACTION statement
          2. SQL-02: Don't leave transactions "dangling "
          3. SQL-03: Avoid use of savepoints —they can obscure program logic and reduce program efficiency
          4. SQL-04: Use an appropriate locking strategy
          5. SQL-05: Keep transactions small
          6. SQL-06: Always reset the NOT FOUND variable after completing a cursor loop
          7. SQL-07: Use SELECT FOR UPDATE when retrieving rows for later update
          8. SQL-08: Avoid including SQL in functions that may be used in SQL
        8. 23.8. Dynamic SQL
          1. DYN-01: Bind, do not concatenate, variable values into dynamic SQL strings
          2. DYN-02: Carefully validate any parameter values that might be used to construct dynamic SQL
          3. DYN-03: Consider the invoker rights method for stored code that executes dynamic SQL
        9. 23.9. Program Construction
          1. PRG-01: Encapsulate business rules and formulas behind accurately named functions
          2. PRG-02: Standardize module structure using function and procedure templates
          3. PRG-03: Limit execution section sizes to a single page (50-60 lines) using modularization
          4. PRG-04: Avoid side-effects in your programs
          5. PRG-05: Avoid deep nesting of conditionals and loops
          6. PRG-06: Limit functions to a single RETURN statement in the executable section
          7. PRG-07: Use stored programs to implement code common to multiple triggers
        10. 23.10. Performance
          1. PER-01: Concentrate on tuning SQL to improve stored program performance
          2. PER-02: Carefully create the best set of indexes for your application
          3. PER-03: Avoid accidental table scans
          4. PER-04: Optimize necessary table scans
          5. PER-05: Avoid using stored programs for computationally expensive routines
          6. PER-06: Move loop invariant expressions outside of loops
          7. PER-07: Optimize conditional structures
          8. PER-08: Structure IF and CASE statements so more likely expressions appear earliest in the list
        11. 23.11. Conclusion
    9. About the Authors
    10. Colophon
    11. SPECIAL OFFER: Upgrade this ebook with O’Reilly