11.6 Data type default value


Official document address: 11.6 Data Type Default Values


Data type specifications can have explicit or implicit default values.

The DEFAULT valueclause in the data type specification explicitly indicates the default value of the column. E.g:

CREATE TABLE t1 (
  i     INT DEFAULT -1,
  c     VARCHAR(10) DEFAULT '',
  price DOUBLE(16,2) DEFAULT 0.00
);

SERIAL DEFAULT VALUEIt is a special case. In the definition of an integer column, it is NOT NULL AUTO_INCREMENT UNIQUEan alias.

DEFAULTCertain aspects of explicit clause handling depend on the version, as described below.

Explicit default value handling in MySQL 8.0.13

DEFAULTThe default value specified in the clause can be a literal constant or an expression. There is one exception. The default value of the expression is enclosed in parentheses to distinguish it from the default value of a literal constant. example:

CREATE TABLE t1 (
  -- 常量默认值
  i INT         DEFAULT 0,
  c VARCHAR(10) DEFAULT '',
  -- 表达式默认值
  f FLOAT       DEFAULT (RAND() * RAND()),
  b BINARY(16)  DEFAULT (UUID_TO_BIN(UUID())),
  d DATE        DEFAULT (CURRENT_DATE + INTERVAL 1 YEAR),
  p POINT       DEFAULT (Point(0,0)),
  j JSON        DEFAULT (JSON_ARRAY())
);

The exception is that for the TIMESTAMPsum DATETIMEcolumn, you can specify a CURRENT_TIMESTAMPfunction as the default value without using parentheses. See 11.2.5 Automatic initialization and update of TIMESTAMP and DATETIME .

BLOB, TEXT, GEOMETRYAnd JSONdata type can only be written when the default value expression is valid, even if the value of the expression is a literal values:

  • This is allowed (the default literal is specified as an expression):
CREATE TABLE t2 (b BLOB DEFAULT ('abc'));
  • This generates an error (the default literal is not specified as an expression):
CREATE TABLE t2 (b BLOB DEFAULT 'abc');

The default value of the expression must follow the following rules. If the expression contains disallowed constructs, an error will occur.

  • Literal values, built-in functions (deterministic and non-deterministic) and operators are allowed.
  • Subqueries, parameters, variables, storage functions, and user-defined functions are not allowed.
  • The default value of the expression cannot depend on AUTO_INCREMENTthe column with the attribute.
  • The expression default value of a column can refer to other columns in the table, but the column referenced by the expression default value must be a column that appears earlier in the table definition. That is, the expression default value cannot contain a forward reference to the generated column or the column with the expression default value.

    Ordering constraints also apply to the use ALTER TABLEof reordering table columns. If the generated table has an expression default value that contains a forward reference to the generated column, or a column that contains an expression default value, the statement will fail.

Note

If any component of the expression default value depends on the SQL mode, then different uses of the table may produce different results, unless the SQL mode is the same in all uses.

For CREATE TABLE ... LIKEsum CREATE TABLE ... SELECT, the target table retains the expression default value of the original table.

If the default value of the expression references an indeterminate function, then any statement that causes the expression to be calculated is unsafe for statement-based replication. This includes INSERTand UPDATEsentences. In this case, if binary logging is disabled, the statement will be executed normally. If binary logging is enabled and binlog_formatset to STATEMENT, the statement will be logged and executed, but a warning message will be written in the error log because the replication slave program may have divergence. When binlog_formatset to MIXEDor ROW, the statement will execute normally.

When inserting a new row, the column with the expression default value can DEFAULTbe inserted by omitting the column name or specifying the column as (just like the column with the text default value):

mysql> CREATE TABLE t4 (uid BINARY(16) DEFAULT (UUID_TO_BIN(UUID())));
mysql> INSERT INTO t4 () VALUES();
mysql> INSERT INTO t4 () VALUES(DEFAULT);
mysql> SELECT BIN_TO_UUID(uid) AS uid FROM t4;
+--------------------------------------+
| uid                                  |
+--------------------------------------+
| f1109174-94c9-11e8-971d-3bf1095aa633 |
| f110cf9a-94c9-11e8-971d-3bf1095aa633 |
+--------------------------------------+

However, use DEFAULT(col_name)to specify the default value of a column, allow the use of a column with a literal default value, and not allow the use of a column with an expression default value.

Not all storage engines allow expression default values. If not, an ER_UNSUPPORTED_ACTION_ON_DEFAULT_VAL_GENERATEDerror will occur .

If the calculated data type of a default value is different from the declared column type, it will be implicitly cast to the declared type according to the usual MySQL type conversion rules. See 12.3 Type Conversion in Expression Evaluation .

Explicit default value handling before MySQL 8.0.13

With one exception, DEFAULTthe default value specified in the clause must be a literal constant; it cannot be a function or expression. For example, this means that the default value of a date column cannot be set to the value of a function such as NOW()or CURRENT_DATE. The exception is that for the TIMESTAMPsum DATETIMEcolumn, you can specify it CURRENT_TIMESTAMPas the default value. See 11.2.5 Automatic initialization and update of TIMESTAMP and DATETIME .

Can not BLOB, TEXT, GEOMETRYand JSONthe data type assigned default values.

If the calculated data type of a default value is different from the declared column type, it will be implicitly cast to the declared type according to the usual MySQL type conversion rules. See 12.3 Type Conversion in Expression Evaluation .

Implicit default value handling

If there is no clear default value in the data type specification, MySQL will determine the default value as follows:

If the column is acceptable NULLas a value, use an explicit DEFAULT NULLclause to define the column.

If the column cannot be NULLused as a value, MySQL will not have a clear DEFAULTclause to define the column.

For data input in DEFAULTa NOT NULLcolumn without an explicit clause , if the INSERTor REPLACEstatement does not contain the value of the column, or the UPDATEstatement sets the column to NULL, MySQL processes the column according to the current SQL mode:

  • If strict SQL mode is enabled, then the transactional table will have an error and the statement will be rolled back. For non-transactional tables, an error occurs, but if an error occurs in the second or subsequent rows of a multi-line statement, the previous row will be inserted.
  • If strict SQL mode is not enabled, MySQL sets the column as the default implicit value of the column data type.

Suppose tthe definition of the table is as follows:

CREATE TABLE t (i INT NOT NULL);

In this example, ithere is no explicit default value, so in strict mode, each of the following statements will generate an error and no rows will be inserted. When strict mode is not used, only the third statement produces an error; the first two statements insert an implicit default value, but the third statement fails because it DEFAULT(i)cannot produce a value:

INSERT INTO t VALUES();
INSERT INTO t VALUES(DEFAULT);
INSERT INTO t VALUES(DEFAULT(i));

See 5.1.11 Server SQL Mode .

For a given table, the SHOW CREATE TABLEstatement shows which columns have explicit DEFAULTclauses.

The implicit default value is defined as follows:

  • For numeric types, the default value is 0, but for AUTO_INCREMENTinteger or floating-point types declared with attributes, the default value is the next value in the sequence.
  • For TIMESTAMPdate and time types other than those, the default value is the appropriate "zero" value for that type. If explicit_defaults_for_timestampsystem variables are enabled , the same TIMESTAMPis true for (see 5.1.8 Server System Variables ). Otherwise, for the first TIMESTAMPcolumn in the table, the default value is the current date and time. See 11.2 Date and Time Data Type .
  • For ENUMother string types, the default value is an empty string. For ENUM, the default value is the first enumerated value.

Guess you like

Origin blog.csdn.net/wb1046329430/article/details/114800056