MySQL - Are “NOT NULL” constraints needed for primary keys?

六眼飞鱼酱① 提交于 2020-01-11 04:32:48

问题


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?


回答1:


(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.




回答2:


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.




回答3:


Primary key must not include nullable columns. auto_increment is not a check constraint, (it is rather a default constraint) , so you cannot remove not null from definition of the column that is part of primary key regardless of presence of auto_increment. You don't have to type not null while creating the table for primary key in mysql, because the engine adds this constraint automatically.




回答4:


WE need not declare explicitly the column as not null because Primary key constraint makes the column NOT NULL. I have checked in Oracle.



来源:https://stackoverflow.com/questions/10462918/mysql-are-not-null-constraints-needed-for-primary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!