Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Delete one row and re-order the others with the correct Sort ID

Tags:

sql

mysql

I have a table which contains a bunch of rows and a sort_order. I was wondering how I can do this so when I delete a row, say I delete the highlighted row with a sort_order of 7. Then instead of 7 just being removed, I would need to change #8 to #7 .. #9 to #8 .. #10 to #9 .. and #11 to #10.

enter image description here

Is something like this possible?

like image 707
Drew Avatar asked Feb 01 '12 15:02

Drew


People also ask

How do I change the order of rows in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.

Can we use ORDER BY in delete query?

You can't DELETE TOP (x) with an ORDER BY.

How do I delete a specific number of rows in MySQL?

To delete rows in a MySQL table, use the DELETE FROM statement: DELETE FROM products WHERE product_id=1; The WHERE clause is optional, but you'll usually want it, unless you really want to delete every row from the table.

Which is the correct order to delete the rows from the table?

Right-click in a table cell, row, or column you want to delete. On the menu, click Delete Cells. To delete one cell, choose Shift cells left or Shift cells up. To delete the row, click Delete entire row.


2 Answers

If you really need to change these values (sort_order will still work with gaps), you can

Delete From t
Where sort_order = 7

and then reduce the remaining entries by 1:

Update t
Set sort_order = sort_order - 1
Where sort_order > 7
like image 63
Peter Lang Avatar answered Oct 10 '22 21:10

Peter Lang


Like this:

Update tablename 
Set sort_order = sort_order - 1 
where sort_order > 7
like image 31
Mahmoud Gamal Avatar answered Oct 10 '22 21:10

Mahmoud Gamal