Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL shift all subsequent rows

Tags:

sql

mysql

I have a table where each row has a primary key ID (ordered ASC), which is just a number. Is there a way to insert a row between two others by first shifting all of the rows below it by one?

like image 952
Niek Avatar asked Apr 14 '26 04:04

Niek


1 Answers

Yes you can like you want to insert row with id 2 you can do so

CREATE TABLE Table1
    (id INT,`test` varchar(10))
;

INSERT INTO Table1
    (id,`test`)
VALUES
    (1,'val'),
    (2,'val'),
    (3,'val')
;

Demo table has 3 records and id 2 is already assigned now you want to add row for id 2 and increment all the ids by 1

update Table1 
set id =id+1
where id >1
ORDER BY id DESC;

INSERT INTO Table1
    (id,`test`)
VALUES
    (2,'my val');

In update query ORDER BY id DESC is necessary for primary key to ignore the duplicate entry error

SELECT * FROM Table1 order by id

Fiddle Demo

like image 71
M Khalid Junaid Avatar answered Apr 17 '26 00:04

M Khalid Junaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!