MySQL columns with DEFAULT NULL - stylistic choice, or is it?

℡╲_俬逩灬. 提交于 2019-11-29 09:09:05

Every database that I've encountered treats NULLs the way that you describe them. When a column accepts NULL values, then not providing a value on INSERT defaults the value to NULL. I believe this is part of the ANSI standard behavior.

As for specifying "NULL" itself. That is a matter of preference. The standard does say that a column allows NULLs unless NOT NULL is specified (at the level of the data definition language). So, the NULL itself is unnecesary, and you have a fourth, equivalent option:

columnname type

NULLs are quite embedded in the SQL language through the ANSI standard. Your third option is the most explicit, but it also looks a bit unusual.

If you are planning on being super-consistent throughout your system, then I would take the path you are on. For every column in every table have NULL or NOT NULL. For all columns that take default values, have the DEFAULT statement.

However, don't expect other people you work with (now or in the future) to readily follow this example. Many would prefer the fourth option in this case simply because it requires less typing and is how all (or almost all) SQL dialects behave.

As documented under Data Type Default Values:

If the column can take NULL as a value, the column is defined with an explicit DEFAULT NULL clause.

(I think they meant implicit, not explicit).

Moreover, as documented under CREATE TABLE Syntax:

If neither NULL nor NOT NULL is specified, the column is treated as though NULL had been specified.

Therefore, in MySQL the following column definitions are all identical:

columnname type
columnname type NULL
columnname type DEFAULT NULL
columnname type NULL DEFAULT NULL

The choice of which to use is a balance between being explicit, and being concise. Depending on the circumstances, I might use any of the above.

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