Creating a table in MySQL requires three steps: Connect to the database. Use the CREATE TABLE statement to specify the table name, column names, data types, and constraints. Execute the CREATE TABLE statement to create the table.
How to create a table in MySQL
Step 1: Connect to the database
First, use a MySQL client tool (such as MySQL Workbench or the command line) to connect to the database where you want to create the table.
Step 2: Write the CREATE TABLE statement
Use the CREATE TABLE statement to create a table. The syntax is as follows:
<code>CREATE TABLE table_name ( column1 data_type [NOT NULL] [DEFAULT default_value], column2 data_type [NOT NULL] [DEFAULT default_value], ... );</code>
where:
table_name
is the name of the new table. column1
, column2
, etc. are the column names of the table. data_type
is the data type of the column (e.g. INT, VARCHAR, DATETIME). NOT NULL
The constraint means that NULL values are not allowed for this column. DEFAULT default_value
Specifies the default value for the column if no value is specified. Step 3: Execute the CREATE TABLE statement
Use the following command to execute the CREATE TABLE statement:
<code>CREATE TABLE my_table ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, age INT DEFAULT 0 );</code>
The columns in the table Description:
id
is a column of INT type, which is automatically incremented by MySQL and marked as NOT NULL. It is often used as a primary key. name
is a column of type VARCHAR(255) that can store text values up to a maximum length of 255 characters and is marked NOT NULL. age
is a column of type INT with a default value of 0. Note:
The above is the detailed content of How to create a table in mysql. For more information, please follow other related articles on the PHP Chinese website!