Home > Database > Mysql Tutorial > body text

**Why does MySQL DELETE with LIMIT and Offset Cause an Error?**

Susan Sarandon
Release: 2024-10-25 11:21:02
Original
210 people have browsed it

**Why does MySQL DELETE with LIMIT and Offset Cause an Error?**

Error Encountered When Using MySQL DELETE Statement with LIMIT

Problem:

When attempting to delete rows from a table using a MySQL DELETE statement with a LIMIT clause, an error is encountered at the offset value in the LIMIT clause. The following query exemplifies the issue:

DELETE FROM `chat_messages` ORDER BY `timestamp` DESC LIMIT 20, 50;
Copy after login

The error message received at the offset value (50) is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 50' at line 1
Copy after login

Solution:

The error occurs because MySQL does not allow specifying an offset in the LIMIT clause of a DELETE statement. Consequently, we must resort to an alternative approach to achieve the desired result.

To delete specific rows from a table based on a range, we can use a subquery nested within the main DELETE query. The following modified query demonstrates this technique:

<code class="sql">DELETE FROM `chat_messages` 
WHERE `id` IN (
    SELECT `id` FROM (
        SELECT `id` FROM `chat_messages`
        ORDER BY `timestamp` DESC
        LIMIT 20, 50
    ) AS `x`
)</code>
Copy after login

In this query, the subquery within the IN clause retrieves the IDs of the rows to be deleted based on the specified range. Assuming the table has a primary key column named id, we can use it to identify each row uniquely.

Note: It's important to implement double nesting to avoid issues with MySQL's inability to select from currently modified tables.

The above is the detailed content of **Why does MySQL DELETE with LIMIT and Offset Cause an Error?**. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!