Home > Database > Mysql Tutorial > How Do I Add a New Column with a Default Value in MySQL?

How Do I Add a New Column with a Default Value in MySQL?

Patricia Arquette
Release: 2024-12-17 19:25:12
Original
493 people have browsed it

How Do I Add a New Column with a Default Value in MySQL?

Adding a New SQL Column with a Default Value

In MySQL, adding a new column to a table with a default value requires the use of the ALTER TABLE statement. The syntax for this statement allows you to specify a default value during column creation.

ALTER TABLE Syntax

The general syntax for adding a new column with a default value is as follows:

ALTER TABLE table_name ADD COLUMN column_name data_type DEFAULT default_value;
Copy after login

In this syntax, table_name represents the table you wish to modify, column_name is the name of the new column, data_type defines the type of data that the column will hold, and default_value specifies the default value for the column.

Example

To add a new column named foo to the table table1 with a default value of 0, you can use the following statement:

ALTER TABLE table1 ADD COLUMN foo INT DEFAULT 0;
Copy after login

Explanation

  • ALTER TABLE table1 specifies that we are modifying the table1 table.
  • ADD COLUMN foo INT adds a new column named foo with a data type of INT.
  • DEFAULT 0 assigns a default value of 0 to the foo column.

Documentation Reference

The syntax provided here is based on the MySQL documentation, which states:

ALTER TABLE tbl_name ADD COLUMN (col_name column_definition,...)
Copy after login

Where column_definition can include a DEFAULT clause:

column_definition:
   data_type [NOT NULL | NULL] [DEFAULT default_value]
   ...
Copy after login

The above is the detailed content of How Do I Add a New Column with a Default Value in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template