Jump to content

[solved] Insert record in middle of table


pikemsu28

Recommended Posts

Is it possible to insert a record into the middle of a table allowing the auto inc id to adjust accordingly? 

example:

Table: Color Schemes

id(auto inc)  value 1           value 2
1                Red               Blue
2                Blue              Green
3                Orange          Black
4                Black             Red

Table: Color Schemes (I need to insert a record between records 2 and 3)

id(auto inc)  value 1           value 2
1                Red               Blue
2                Blue              Green
3                Green            Orange (inserted record and causes ID of following records to change)
4                Orange          Black
5                Black             Red

I hope this makes sense.

Thanks,
Jason

**Thanks to who all replied.
Link to comment
Share on other sites

I want to say no, just because you shouldn't. Auto inc PK's aren't meant to be used like this. You could do this on the one table but it would mess up every table in your database that uses that id as a foreign key. Use instead a separate field, I usually call mine sort_order for that.

Then before the insert:
[code]
UPDATE color_schemes SET sort_order = sort_order + 1 WHERE sort_order > 2[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.