12

Lets say we have table A with just one column, id(which is the primary key)

How do we insert a new row into the table without specifying an id?

I tried this

INSERT INTO A (`id`) VALUES (NULL)

and it doesn't work

Edit: I forgot to mention that id, the primary key has the auto_increment and NOT NULL attribute.

Edit 2: The exact error when running the query above is

Column 'id' cannot be null
6
  • Why not share with us how exactly it's failing to work? Commented May 11, 2011 at 9:34
  • PK field does not allow duplicate values nor NULL values Commented May 11, 2011 at 9:34
  • Primary key fields must be NOT NULL. Commented May 11, 2011 at 9:36
  • @arvinsim - Your description of the set-up looks correct. You've probably failed to do some of the steps you claim you've done. Commented May 11, 2011 at 9:42
  • 1
    can you post your table definition pls :) Commented May 11, 2011 at 10:25

5 Answers 5

19

As soon as 'id' as the auto-increment enable (assuming ID is an integer), you can just do:

INSERT INTO A (id) values (null)

and 'id' will keep incrementing each time.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't think this works. I tried it and it tried to insert the digit 0. Since I was trying to insert 5 times, it produces a duplicate entry error.
@arvinsim: There must be some problem with your setup. MySQL accepts both NULL and 0 as values for an auto_increment column, and interprets them as meaning "use the next ID".
This worked for me with a MySQL database. It does in fact increment the id each time.
The problem comes to get that number, sigh!!
6

only works if you're using an auto_increment primary key (PK) as every PK must have a unique, non null value.

drop table if exists A;
create table A
(
id int unsigned not null auto_increment primary key
)
engine=innodb;

insert into A (id) values (null),(null);

mysql> select * from A order by id;
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.00 sec)

2 Comments

Yes it is an auto-incrementing field
Unless I'm missing something, that's the set-up described in the question :-?
0

I had a similar issue, then I noticed that I didn't apply the changes when I changed id to primary key + not null + auto incremental.

Comments

0
INSERT INTO `table` () VALUES (); 

is working too.

Comments

-1

Try it without the ``.. As in:

INSERT INTO A(sid) VALUES(NULL); //i used sid instead of id...

worked fine for me..

Also wwhile creating the table A, specify unique(sid)... i.e

create table A(sid int(3) not null auto_increment unique(sid));

1 Comment

Quoting style should not change anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.