Click here to Skip to main content
15,904,926 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a MYSQL table having 50 rows.
Now I need to add a row between 5 and 6.
But the primary key should change after that 5, new row-6 ,after-wards 7,8
I tried insert row - shows duplicate primary key

How can I add a row between two rows in existing table?

Thanks in advance
Saranya1388
Posted
Updated 25-Oct-10 22:40pm
v2
Comments
Dalek Dave 26-Oct-10 4:40am    
Edited for Grammar and Readability.

1 solution

If I read you right, you have a mySql table with rows thus:
1 me
2 you
3 them
4 him
5 her
6 it
7 whom
8 who
You want to change this to:
1 me
2 you
3 them
4 him
5 her
6 my new row
7 it
8 whom
9 who
If this is correct then there is no automatic way to do it. It may not even be possible, depending on your DB design. Did you use auto number? If so, then no, you can't do it. Is this field used in any other tables? If so, then no, I don't recommend it.
If not, then you have to:
1) Retrieve all records in the table.
2) Find the last number that needs to be updated.
3) Working backwards from this, increment each number by one, using SQL update commands, until you reach your insert point.
4) Insert your new record.

However, I would really not recommend this. Instead, if you need an order by field, then add one. And update it as described above.
In a real life situation, with multi-user database, this kind of thing is seriously unhealthy for data integrity!
 
Share this answer
 
Comments
Dalek Dave 26-Oct-10 4:41am    
It would seriously take a lot of time to run too, especially in a large DB.
Farook Abrar 07 29-Oct-21 6:31am    
ok

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900