Home  >  Article  >  Database  >  How to write the default value in mysql

How to write the default value in mysql

下次还敢
下次还敢Original
2024-04-26 06:18:15540browse

How to set default values ​​for columns in MySQL: specify the NOT NULL DEFAULT clause when creating the table, such as: CREATE TABLE users (name VARCHAR(255) NOT NULL DEFAULT 'John Doe'); use the ALTER TABLE statement Modify an existing table: ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT default_value, such as: ALTER TABLE users ALTER COLUMN name S

How to write the default value in mysql

How to set default in MySQL Value

Setting a default value for a column in MySQL is as simple as specifying DEFAULT## when creating a table or when modifying an existing table using the ALTER TABLE statement. # clause is enough.

Set default values ​​when creating a table

<code class="sql">CREATE TABLE table_name (
  column_name data_type NOT NULL DEFAULT default_value
);</code>
For example:

<code class="sql">CREATE TABLE users (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL DEFAULT 'John Doe'
);</code>
This will be created in a table named

users A column named name with its default value set to John Doe.

Use the ALTER TABLE statement to modify the default value

<code class="sql">ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT default_value;</code>
For example:

<code class="sql">ALTER TABLE users ALTER COLUMN name SET DEFAULT 'Jane Doe';</code>
This will modify the table

users in The default value for the name column, set it to Jane Doe.

Default value type

The default value can be any MySQL data type, including:

    Number (integer and floating point)
  • String
  • Date and time
  • Boolean
  • NULL (indicates that the column can be empty)

Note:

    The default value will only be applied when inserting a new row and will not affect existing rows.
  • If the inserted value matches the default value, MySQL ignores the default value and inserts the explicit value provided.
  • The default value can always be modified at any time using the
  • ALTER TABLE statement.

The above is the detailed content of How to write the default value in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn