Guides

Step-by-step tutorials and practical fixes for servers, systems, databases, and daily technical work.
Database Guides

Update MySQL Order Column Sequentially

Assign ordered values using a single SQL query.

Before you start

Backup your data before running UPDATE queries.
Make sure ORDER BY condition is correct.
Test on a small dataset first.

Step-by-step

SQL
SET @cnt = 0;

UPDATE wp_bwg_image
SET `order` = @cnt := @cnt + 1
WHERE gallery_id = '12'
ORDER BY `id` DESC;
What it does

Assigns sequential numbers based on id descending order.

Common issues

Wrong order

Check ORDER BY condition carefully.

Unexpected values

Make sure @cnt is initialized.

Data overwritten

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

  1. Initialize a counter variable.
  2. Run UPDATE query with ORDER BY.
  3. 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.