Why MySQL UPDATE Affected Rows Can Mislead Your Business Logic
In MySQL, an UPDATE that modifies no actual data returns an affected‑rows count of zero, making it unreliable for business logic that distinguishes between unchanged rows and non‑existent records, so developers should avoid using this count for critical decisions.
In typical business systems, developers use MySQL UPDATE statements and often rely on the number of affected rows to make further decisions, as shown in the pseudo‑code example:
if (xxxMapper.updateByPrimaryKeySelective(entity) > 0) {
// update succeeded, perform other business processing
}However, MySQL only reports a positive affected‑row count when the statement actually changes data. If a table contains a single row (ID = 1) and an UPDATE sets the column to its current value, the first execution reports 1 affected row, but a subsequent identical execution reports 0 because no data changed.
This means that when the incoming data matches the existing values, MySQL returns 0, which is indistinguishable from the case where the target row does not exist at all.
Conclusion: do not use the affected‑row count of an UPDATE statement for critical business judgments.
Images illustrate the table before and after the update and the resulting row‑count output.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
