shinichi
shinichi

Reputation: 33

How to insert a new row and increase a column based on its previous row's value?

Table name: ORDERTABLE

ID (PK) || ORDER_ID || ITEMNAME || QTY
=======================================
1       ||    1     ||  apple   ||  2
2       ||    1     ||  orange  ||  5
3       ||    2     ||  pear    ||  1
4       ||    2     ||  grapes  ||  1
5       ||    2     ||  melon   ||  1

How do I insert a new row based the previous number of ORDER_ID in SQL?

So that I will get this:

ID (PK) || ORDER_ID || ITEMNAME || QTY
=======================================
1       ||    1     ||  apple   ||  2
2       ||    1     ||  orange  ||  5
3       ||    2     ||  pear    ||  1
4       ||    2     ||  grapes  ||  4
5       ||    2     ||  melon   ||  2
6       ||    3     ||  mango   ||  3

Currently my query string is:

insert into ORDERTABLE(ORDER_ID,ITEMNAME,QTY) values (LAST()+1, 'mango',3)

only to get this error:

wrong number of arguments used with function in query expression

Upvotes: 1

Views: 707

Answers (1)

INSERT INTO ORDERTABLE (ORDER_ID, ITEMNAME, QTY) SELECT MAX(ORDER_ID)+1, 'mango', '3' FROM ORDERTABLE;

Upvotes: 2

Related Questions