Home > Database > Mysql Tutorial > body text

How to create a table in mysql

下次还敢
Release: 2024-04-14 18:21:48
Original
1098 people have browsed it

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

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>
Copy after login

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>
Copy after login

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:

  • Make sure the data type of the column matches the data you want to store.
  • Consider using appropriate constraints (such as NOT NULL) to ensure data integrity.
  • The AUTO_INCREMENT keyword can be used to automatically generate a unique ID when inserting a new row.

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!

Related labels:
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