Search code examples
mysqlsqlmysql-error-1064

#1062 - Duplicate entry '0' for key 'PRIMARY'


I have a problem with mysql table while try to insert values in database.

I followed this tutorial

http://sqllessons.com/categories.html

and created table like the table from tutorial

table code

create table categories
( id       integer     not null  primary key 
, name     varchar(37) not null
, parentid integer     null
, foreign key parentid_fk (parentid) 
      references categories (id)
);

error SQL query: Edit Edit

INSERT INTO `mydb`.`categories` (
`id` ,
`name` ,
`parentid`
)
VALUES (
'', 'groceries', NULL
), (
'', 'snacks', NULL
)

MySQL said: Documentation
#1062 - Duplicate entry '0' for key 'PRIMARY'

Help me to solve this.


Solution

  • Declare the value to be auto incrementing and don't insert it. So:

    create table categories (
        id       integer     not null  auto_increment primary key,
        name     varchar(37) not null,
        parentid integer     null,
        foreign key parentid_fk (parentid) references categories (id)
    );
    

    And then:

    INSERT INTO `mydb`.`categories` (`name`, `parentid`)
        VALUES ('groceries', NULL),
               ('snacks', NULL);