Skip to Main Content
MySQL Stored Procedure Programming
book

MySQL Stored Procedure Programming

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

Name

SQL-07: Use SELECT FOR UPDATE when retrieving rows for later update

Synopsis

Use the SELECT FOR UPDATE statement to request that locks be placed on all rows identified by the query. You should do this whenever you expect to change some or all of those rows, and you don't want another session to change them out from under you. Any other session trying to update the rows, or lock the rows (perhaps using FOR UPDATE), will have to wait.

Example

Here we are processing a special bonus payment for needy employees. We issue the FOR UPDATE clause so that the rows concerned are locked until our transaction completes:

    CREATE PROCEDURE needy_bonus(  )
    BEGIN
      DECLARE  v_employee_id INT;
      DECLARE  v_salary      NUMERIC(8,2);
      DECLARE  v_last_emp    INT DEFAULT 0;

      DECLARE emp_csr CURSOR FOR
       SELECT employee_id,salary
         FROM employees
        WHERE salary <45000
          FOR UPDATE;

      DECLARE CONTINUE HANDLER FOR NOT FOUND SET  v_last_emp=1;

      START TRANSACTION;
        OPEN emp_csr;
        emp_loop:LOOP
          FETCH emp_csr INTO  v_employee_id, v_salary;
          IF  v_last_emp THEN
            LEAVE emp_loop;
          END IF;
          CALL grant_raise( v_employee_id, v_salary);
        END LOOP emp_loop;
        CLOSE emp_csr;
        SET  v_last_emp=0;

      COMMIT;

    END;

You can also use the LOCK IN SHARE MODE clause to lock the rows against update but continue to allow reads.

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 Concurrency: Locking and Transactions for MySQL Developers and DBAs

MySQL Concurrency: Locking and Transactions for MySQL Developers and DBAs

Jesper Wisborg Krogh
MySQL 8 Administrator???s Guide

MySQL 8 Administrator???s Guide

Chintan Mehta, Hetal Oza, Subhash Shah, Ravi Shah
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal
Learning MySQL, 2nd Edition

Learning MySQL, 2nd Edition

Vinicius M. Grippa, Sergey Kuzmichev

Publisher Resources

ISBN: 0596100892Supplemental ContentErrata Page