Inserting NULL into NOT NULL columns with Default Value

后端 未结 5 1349
清酒与你
清酒与你 2021-02-15 06:16

For a bit of background, we use Zend Framework 2 and Doctrine at work. Doctrine will always insert NULL for values we do not popul

5条回答
  •  心在旅途
    2021-02-15 07:22

    If you leave out the column (both name and value) from the statement, then the default value will be used.

    Some related advice:

    • Don't have any "non-empty" defaults in your tables, and don't have non-null defaults for nullable columns. Let all values be set from the application.
    • Don't put business logic on the database-side.

    Only define a default if really needed, and only for non-nullable columns. And remove the default when no longer needed. (they come in handy with alter table runs, to set the value of a new column, but then immediately run a new (cheap!) alter to remove the default)

    The "empty" mentioned above, is related to the type: - 0 for numerical columns, - '' for varchar/varbinary columns, - '1970-01-01 12:34:56' for timestamps, - etc.

    That saves the application many round trips to the database. If a created row is fully predictable, then the application doesn't need to read it after creating, to find out what it has become. (this assumes: no triggers, no cascading)

    With MySQL we make only a few specific exceptions to those strict rules:

    • Columns called mysql_row_foo, are only set by the database. Examples:

        mysql_row_created_at  timestamp(6)  not null  default '1970-01-01 12:34:56.000000',
        mysql_row_updated_at  timestamp(6)  null      default null  on update current_timestamp,
      

    • Unique indexes on not-null columns are welcome, to prevent duplicate data. For example on lookup.brand.name in a table lookup.brand that looks like (id++, name).

    The mysql_row_foo columns are like column attributes. They are used by data sync tools, for example. General applications don't read them, and they store their application-side timestamps as epoch values. Examples:

     valid_until_epoch   int unsigned  not null  default 0,
     last_seen_epoch_ms  bigint        not null  default 0,
    

提交回复
热议问题