9

I'm getting ORA-00947: not enough values from the query below:

insert into tableb
(colA, colb, colc, cold)
select
(select max(rec_no)+1 from tableb)
F2,
F3,
F4
from tablea;

Can someone point me to the correct way to include a sub query for an inser into/select statement?

Thanks

3
  • 5
    I hope you are not trying to create a unique ID using that max() approache. Because it will simply not work. Better use a sequence Commented Dec 12, 2012 at 11:55
  • @a_horse_with_no_name actually this is what I was attempting. Can you provide a link to a discussion about how I'd achieve this with a sequence? Thanks Commented Dec 12, 2012 at 11:58
  • 1
    See my answer. The sequence still won't solve the problem what to do if tablea is empty (as David Aldridge mentioned) Commented Dec 12, 2012 at 12:06

2 Answers 2

16

You are just missing a comma. As it is, Oracle thinks F2 is the name of your sub-select.

insert into tableb
(colA, colb, colc, cold)
select
(select max(rec_no)+1 from tableb) ,   -- comma here
F2,
F3,
F4
from tablea;
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! I was going crazy!
Won't work if there are no rows in the table to begin with, or multiple sessions are running that code at the same time. Unfortunately the approach is fundamentally flawed.
@David Aldridge the tables aren't empty, I'm the only one running this code. Is there a better method?
If you want to generate unique record numbers, consider using a sequence.
8

The only reliable, fast and scalable way to generate unique IDs is using sequences.

The reason why the max() "solution" won't work, is a transaction will not see uncommitted changes from another transaction. So two concurrent transactions can wind up using the same value for max() which in turn will generate duplicate id values.

To create the values from a sequence in your case, you obviously need to first create a sequence:

create sequence seq_b;

Then use that sequence in your select statement:

insert into tableb
  (colA, colb, colc, cold)
select seq_b.nextval,
       F2,
       F3,
       F4
from tablea;

1 Comment

Thanks for the explantion and the help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.