What’s the point of adding NOT NULL to primary key field in MySQL?

What’s the point of adding NOT NULL to a primary key field? Primary key is already not null + unique.

Here is an example:

CREATE TABLE student (
  id int(11) AUTO_INCREMENT NOT NULL,
  name varchar(255),
  PRIMARY KEY(id)
)

Why not to define it like this instead:

CREATE TABLE student (
  id int(11) AUTO_INCREMENT,
  name varchar(255),
  PRIMARY KEY(id)
)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.

Method 3

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x