tags:

views:

45

answers:

3

Why NOT NULL add to primary key field?(primary key is already not null+unique)

Example for NOT NULL id field:

create table student
(
 id int(11) AUTO_INCREMENT NOT NULL,
 name varchar(255),
 PRIMARY KEY(id)
)

Instead Just:

create table student
(
 id int(11) AUTO_INCREMENT,
 name varchar(255),
 PRIMARY KEY(id)
)

Edit: I add AUTO_INCREMENT.

Thansk

+2  A: 

NULL is not equivalent to NULL(as NULL indicates an unknown or absent value), so you will be permitted to have multiple records that have NULL for the id, even though there's a primary key / unique constraint defined, hence the use of NOT NULL. That's if MySql even allows you to define a primary key on a nullable field.

In addition, as a primary key is often used in a foreign key in other tables, having one or more NULL values wouldn't make sense.

Rob
`NULL` on `PRIMARY KEY` violate ISO standard and considered as a bug in mysql: http://bugs.mysql.com/bug.php?id=390 . See http://en.wikipedia.org/wiki/Unique_key for the justification of NOT NULL
J-16 SDiZ
+3  A: 

They are the same. Primary key got NOT NULL automatically.

J-16 SDiZ
soo why peaple add NOT NULL??
Yosef
@Yosef this is just a matter of style. And `mysqldump` add this `NOT NULL` when dump a table, because of a bug for allowing NULL in mysql.
J-16 SDiZ
+1  A: 

You are asking, why do people bother adding the NOT NULL when it is unnecessary? Just because it is good style, I guess. And makes it explicit to the reader.

Hammerite