Update MySQL Order Column Sequentially
Assign ordered values using a single SQL query.
Before you start
Step-by-step
SET @cnt = 0;
UPDATE wp_bwg_image
SET `order` = @cnt := @cnt + 1
WHERE gallery_id = '12'
ORDER BY `id` DESC;
Assigns sequential numbers based on id descending order.
Common issues
Check ORDER BY condition carefully.
Make sure @cnt is initialized.
This query updates all matching rows.
About this guide
This guide shows how to update a column in MySQL sequentially based on a specific order. It is commonly used to reset ordering values in tables.
How to follow this guide
- Initialize a counter variable.
- Run UPDATE query with ORDER BY.
- Verify that values are assigned sequentially.
Why use this method?
This method helps maintain ordered data such as image lists, menu positions, or custom sorting fields.
Frequently Asked Questions
What is @cnt in MySQL?
It is a user-defined variable used to generate sequential numbers.
Does ORDER BY work in UPDATE?
Yes, MySQL supports ORDER BY in UPDATE statements.
Can this break existing order?
Yes, it overwrites values, so use carefully.
Is this safe for production?
Test first before running on production data.