Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert manually into a table by SQL statement, but key is autoincremented

Let's say I have a table of users and the id column is the primary key and auto incremented.

I want to just try and add user manually by this statement:

INSERT INTO table_name (id, username, password)  
VALUES (?, Mike, Mike);

but I don't want to specify the ? value, just want to add to the next row.

Thanks everyone, I forgot to set the id column to auto increment. it works now.

like image 930
Mike Avatar asked Oct 07 '12 16:10

Mike


2 Answers

So just don't use it...do it like this..

And be sure you use single quotes for inserting strings

INSERT INTO table_name (username, password)
VALUES ('Mike', 'Mike');

As you said your field is auto incremented, SQL will automatically increment the value of the id field by 1

like image 147
Mr. Alien Avatar answered Oct 02 '22 00:10

Mr. Alien


If you want to manually insert a value to an auto incremented column you can use the IDENTITY_INSERT of sql. for example

SET IDENTITY_INSERT MyTable ON
insert into MyTable(id, name) values (1,'asdf');
insert into MyTable(id, name) values (3,'htgfds');
insert into MyTable(id, name) values (123,'dsfg');
SET IDENTITY_INSERT MyTable OFF

you can read more here IDENTITY_INSERT

like image 27
Mr T. Avatar answered Oct 01 '22 22:10

Mr T.