Select * for update lock table in MySQL

Source: Internet
Author: User

I have previously introduced the usage of SELECT... FOR UPDATE, but the locking data is a distinction. Because InnoDB defaults to Row-Level Lock, MySQL will only execute Row lock (only Lock the selected data example) If a specified Primary Key is specified explicitly ), otherwise, MySQL will execute Table Lock (Lock the entire data form ).

For example:

Assume that there is a form products, which contains two columns: id and name. id is the primary key.

Example 1: (specify the primary key and use this document, row lock)

SELECT * FROM products WHERE id = '3' for update;

Example 2: (specify a primary key. If no data is found, no lock is required)

SELECT * FROM products WHERE id = '-1' for update;

Example 2: (no primary key, table lock)

SELECT * FROM products WHERE name = 'mouse 'for update;

Example 3: (the primary key is not clear, table lock)

SELECT * FROM products WHERE id <> '3' for update;

Example 4: (the primary key is not clear, table lock)

SELECT * FROM products WHERE id LIKE '3' for update;

NOTE 1: for update only applies to InnoDB and must be in the transaction block (BEGIN/COMMIT.

NOTE 2: To test the locking status, you can use the Command Mode of MySQL to open two windows for testing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.