postgresql - Insert into postgres SQL -


is there way insert new record table doesn't have auto-increment id without entering id. want id lastid+1.

insert lists values (id,'ko','sph', '5') //new id

don't that! ever! don't think doing that!

this wrong solution may seems (it doesn't) work you:

insert lists values ((select max(id)+1 lists),'ko','sph', '5'); 

but, if try insert @ same time you, both same id, cause invalid result. should use sequence or more reliable mechanism (an auxiliary table common when can't have holes in sequence, has drawbacks [it lock]). can use serial data type make easier (it creates sequence underneath):

create table lists(id serial, col2 text, col3 text, ...); -- if don't specify "id", autogenerate you: insert lists(col2, col3, ...) values('ko','sph', ...); -- can specify using default (the same above): insert lists(id, col2, col3, ...) values(default, 'ko','sph', ...); 

if really, really, really, can't create , use sequence, can above, have handle exception (assuming id field pk or uk, , using read committed transaction), (in pl/pgsql):

declare     inserted bool = false; begin     while not inserted loop;         begin             insert lists             values ((select coalesce(max(id),0)+1 lists),'ko','sph', '5');             inserted = true;         exception             when unique_violation                 null; -- nothing, try again         end;     end loop; end; 

but again, highly recommend avoid it: use sequence , happy... =d

also, know example, use explicit columns list on insert into clause.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -