Home >Database >Mysql Tutorial >How to Delete a Range of Rows in MySQL without Using OFFSET in DELETE Statement?
Deleting Rows with a Range in MySQL
When attempting to delete a specific range of rows from a table using the LIMIT clause in MySQL, an error can occur. To illustrate, the following query aims to delete a range of 50 rows, starting from the 20th row ordered by timestamp in descending order:
DELETE FROM `chat_messages` ORDER BY `timestamp` DESC LIMIT 20, 50;
However, upon executing this query, an error message is encountered due to an invalid syntax, specifically at the OFFSET value (50).
Limitation of LIMIT Clause in DELETE Statement
The root cause of the error lies in the inability to use OFFSET in the LIMIT clause of DELETE statements. This is a significant distinction from SELECT statements, which allow both LIMIT and OFFSET to specify the starting point and number of rows to retrieve.
Workaround for Range Deletion
To circumvent this limitation, a workaround is necessary. By utilizing a subquery nested within the DELETE statement, the range of rows can be accurately targeted and removed. This approach involves the following steps:
Here's an example of a modified query using this workaround:
DELETE FROM `chat_messages` WHERE `id` IN ( SELECT `id` FROM ( SELECT `id` FROM `chat_messages` ORDER BY `timestamp` DESC LIMIT 20, 50 ) AS `x` )
In this query, the primary key column id is assumed, although it can be modified to the appropriate column name in your specific scenario.
The above is the detailed content of How to Delete a Range of Rows in MySQL without Using OFFSET in DELETE Statement?. For more information, please follow other related articles on the PHP Chinese website!