Home >Database >Mysql Tutorial >How to use sql to create a new table in mysql database
To create a new table in MySQL, you need to follow the following steps: connect to the database; write the CREATE TABLE statement, specify the table name, column name, data type, and set constraints and default values; execute the CREATE TABLE statement; Use SHOW TABLES to verify that the new table has been created.
How to use SQL to create a new table in MySQL database
Creating a new table in MySQL database is very simple, Just use the following steps:
1. Connect to the database
First, connect to your MySQL database using the following command:
<code>mysql -u <用户名> -p</code>
Where:
<Username>
is your MySQL username-p
means you need to enter the password2. Write a CREATE TABLE statement
Next, write a CREATE TABLE statement to create a new table. The basic syntax of this statement is:
<code>CREATE TABLE <表名> ( <列名> <数据类型> [NOT NULL] [DEFAULT <默认值>] );</code>
where:
<Table name>
is the name of the new table you want to create<Column Name>
is the name of the column you want to create <Data Type>
is the name you want to use for the column Data type (for example, INT, VARCHAR, DATE, etc.) NOT NULL
Constraint means that the column cannot contain NULL values DEFAULT <Default value>
Set to use a value other than NULL when inserting the column 3. Execute the CREATE TABLE statement
After writing the CREATE TABLE statement, use the following Command to execute it:
<code>CREATE TABLE <表名> ( <列名> <数据类型> [NOT NULL] [DEFAULT <默认值>] );</code>
For example, to create a table named customers
with three columns: id
(primary key), name
(name) and email
(email address), you can use the following statement:
<code>CREATE TABLE customers ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL );</code>
4. Verify the new table
Execute CREATE After the TABLE statement, you can verify that the new table was created using the following command:
<code>SHOW TABLES;</code>
You should see the newly created table name listed in the results.
The above is the detailed content of How to use sql to create a new table in mysql database. For more information, please follow other related articles on the PHP Chinese website!