Home > Database > Mysql Tutorial > How to Use LIMIT in MySQL UPDATE Queries?

How to Use LIMIT in MySQL UPDATE Queries?

Barbara Streisand
Release: 2024-11-30 17:31:12
Original
644 people have browsed it

How to Use LIMIT in MySQL UPDATE Queries?

Updating Rows with Limit in MySQL

In MySQL, using the LIMIT clause in an UPDATE query can be confusing. Here, we provide a detailed explanation of its usage and address related questions.

Query with LIMIT

To update rows within a specific range, you can use the following syntax:

UPDATE table_name SET column_name = value
WHERE id IN (
    SELECT id FROM (
        SELECT id FROM table_name
        ORDER BY id ASC
        LIMIT start_row, row_count
    ) tmp
)
Copy after login

For example, to update rows from 1001 to 1100, use:

UPDATE table_name SET p_id = 3
WHERE id IN (
    SELECT id FROM (
        SELECT id FROM table_name
        ORDER BY id ASC
        LIMIT 1001, 1000
    ) tmp
)
Copy after login

Invalid Query

The query you provided (UPDATE oltp_db.users SET p_id = 3 LIMIT 1001, 1000) is invalid because LIMIT cannot be used directly in an UPDATE statement. It must be applied within a subquery as shown above.

Updating Null Values

If the p_id column contains NULL values, the following query will not work:

UPDATE `oltp_db`.`users` SET p_id = 3 WHERE p_id = null
Copy after login

To update NULL values, you can use the IS NULL condition:

UPDATE `oltp_db`.`users` SET p_id = 3 WHERE p_id IS NULL
Copy after login

The above is the detailed content of How to Use LIMIT in MySQL UPDATE Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template