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

后端 未结 2 1575
孤独总比滥情好
孤独总比滥情好 2020-12-18 18:37

In many flavors of SQL, there are three ways you can implicitly set a column to NULL on every row insertion. These are:

columnname type NULL
columnname type          


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 19:00

    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.

提交回复
热议问题