Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Are "NOT NULL" constraints needed for primary keys?

is it necessary to declare "NOT NULL" constraints for primary keys in the MySQL database? A primary key cannot have NULL values because it auto_increments anyway and automatically fills the field record. So am I correct in saying this mean I can remove the "NOT NULL" constraint for my primary keys?

like image 906
Ben Aidley Avatar asked May 05 '12 14:05

Ben Aidley


2 Answers

(As you've tagged your question mysql.) In MySQL, you don't have to do it explicitly. From the manual:

A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently).

Of course, just because you don't have to doesn't mean you might not want to for clarity, etc.

like image 89
T.J. Crowder Avatar answered Sep 17 '22 18:09

T.J. Crowder


Yes and no You can remove "Not null", that won't remove the constraint though. Personally I'd leave them in, you gain nothing worthwhile from taking them out.

like image 44
Tony Hopkinson Avatar answered Sep 17 '22 18:09

Tony Hopkinson