11.6 Data Type Default Values (original) (raw)

Data type specifications can have explicit or implicit default values.

Explicit Default Handling

A DEFAULT _`value`_ clause in a data type specification explicitly indicates a default value for a column. Examples:

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

SERIAL DEFAULT VALUE is a special case. In the definition of an integer column, it is an alias forNOT NULL AUTO_INCREMENT UNIQUE.

With one exception, the default value specified in aDEFAULT clause must be a literal constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that, for TIMESTAMP andDATETIME columns, you can specifyCURRENT_TIMESTAMP as the default. See Section 11.2.6, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”.

The BLOB,TEXT,GEOMETRY, andJSON data types cannot be assigned a default value.

Implicit Default Handling

If a data type specification includes no explicitDEFAULT value, MySQL determines the default value as follows:

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

If the column cannot take NULL as a value, MySQL defines the column with no explicitDEFAULT clause.

For data entry into a NOT NULL column that has no explicit DEFAULT clause, if anINSERT orREPLACE statement includes no value for the column, or anUPDATE statement sets the column to NULL, MySQL handles the column according to the SQL mode in effect at the time:

Suppose that a table t is defined as follows:

CREATE TABLE t (i INT NOT NULL);

In this case, i has no explicit default, so in strict mode each of the following statements produce an error and no row is inserted. When not using strict mode, only the third statement produces an error; the implicit default is inserted for the first two statements, but the third fails because DEFAULT(i) cannot produce a value:

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

See Section 5.1.10, “Server SQL Modes”.

For a given table, the SHOW CREATE TABLE statement displays which columns have an explicit DEFAULT clause.

Implicit defaults are defined as follows: