| SQL - Questions and Answers Have a SQL question? Post it here. First do a search to see if someone hasn't already answered it. |
|
||||||
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread |
|
|||
How to select highest value and then create new object with that value +1?I'm a real newb on sql and can't find any solution to my problem.
I'm having a db with a table Item and in that table are quite a few collumns. One of them is named IID What I want to do is the following: Select the highest IID, then add 1 (say the max IID is 50, I want to use 51) and fill in all the collumns. I know how to select that highest IID, I know how to fill in all the other values, I just can't figure out how to add 1 to that IID :s I have this: SELECT * FROM Item WHERE IID = (SELECT MAX(IID) FROM Item) INSERT INTO Item (IID, all the rest of the collumns here ) VALUES ( no idea what will come here, again all the rest of the values here) I'm pretty sure I'll need some extra stuff to make it work but again, I can't figure it out Thx already |
|
|||
|
This should work it most dialects:
INSERT INTO item (iid) SELECT max(iid) +1 FROM item;I find it simpler, but it assumes the IID column is defined NOT NULL. Here is another attempt, which does not make that assumption:
INSERT INTO item (iid) SELECT max(case when iid IS NULL then -1 else iid end) +1 FROM item;But what if the table is initially empty? As the function MAX is applied to an empty set, it will return the null value, which will become the value of the first IID. Let us again consider the first version (with the NOT NULL assumption):
nsert INTO item (iid) SELECT case when hm IS NULL then 0 else hm end FROM (SELECT max(iid) + 1 FROM item ) AS t |
![]() |
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| How do I select the highest 20 to 30 values? | ben | SQL - Questions and Answers | 4 | 01-18-2008 10:56 AM |