|
Custom Search
| |
|
How to update top N rows of data in MySQL The update statement in MySQL supports the use of LIMIT clause to specify the number of rows that can be updated. In this tutorial, we use two examples to show how to use them effectively. Practice #1: Update top 2 rows. The following update query increases the UnitPrice by 10% for the first two products in the Condiments category (ordered by ProductID). To instruct MySQL how to pick the products for update, we use ORDER BY clause. To update only 2 rows, we use LIMIT clause. In this query, the data is sorted by ProductID in ascending order and the first 2 products are chosen by the LIMIT 2 clause. Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. UPDATE products Before update - the screenshot below shows that the UnitPrice for the two products are $10 and $22 (for CategoryID 2 only - Condiments).
After update - 2 rows updated. Now the UnitPrice for the two products are increased by 10% to $11 and $24.2
Practice #2: Update UnitPrice for the top 5 most expensive products. The following update query reduces the UnitPrice by 10% for the top 5 most expensive products. Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. UPDATE products Before update - the screenshot below shows the UnitPrice for the top 5 most expensive products.
After update - 5 rows updated. UnitPrice is reduced by 10% for the top 5 most expensive products.
Happy Coding!
Other tutorials in this category 1. Update Statement in MySQL |
Copyright © 2024 GeeksEngine.com. All Rights Reserved. This website is hosted by HostGator. No portion may be reproduced without my written permission. Software and hardware names mentioned on this site are registered trademarks of their respective companies. Should any right be infringed, it is totally unintentional. Drop me an email and I will promptly and gladly rectify it. |
Home | Feedback | Terms of Use | Privacy Policy |