0
tablename =  zones

  ID     sort_order  area_name
======== =========   =========
  1        1          aaaa
  3        2          bbbb
  5        3          cccc
  7        4          dddd
  8        5          eeeee

i need to add a new area_name

eg: ffff in place of sort_order = 3.

and re-arrange the remaining areas sort_orders accordingly as shown below

  ID     sort_order  area_name
======== =========   =========
  1        1          aaaa
  3        2          bbbb
  9        3          ffff
  5        4          cccc
  7        5          dddd
  8        6          eeeee

need sql query for this

1
  • 2
    Update 'cccc' with 'ffff' and add new row with 'eeee'. That's the logic. Now you need is one update query and one Insert query. Try it. Commented Jun 27, 2018 at 8:33

2 Answers 2

1

Use UPDATE and INSERT. I'm assuming that ID is auto-generated. The UPDATE makes room for the new record in the sort_order sequence and then you can easily insert.

 UPDATE zones
 SET sort_order = sort_order + 1
 WHERE sort_order >= 3

 INSERT INTO zones(sort_order , area_name) 
 VALUES (3, 'ffff')

However, if the zones table is heavily inserted then you will experience a lot of blocking wait.

Sign up to request clarification or add additional context in comments.

Comments

1

You need 2 queries to do that.. First of all you update the sort_orders of the existing entries and insert the new entry afterwards:

UPDATE zones SET sort_order=sort_order + 1 WHERE sort_order >= 3;
INSERT INTO zones VALUES (NULL, 3, 'ffff')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.