Home  >  Article  >  Database  >  How to create a table using sql statement in mysql

How to create a table using sql statement in mysql

下次还敢
下次还敢Original
2024-04-22 20:03:56391browse

To create a table in MySQL using SQL, you can use the CREATE TABLE statement. The syntax is: CREATE TABLE table_name (column_name data_type [NOT NULL] [DEFAULT default_value], ...). Among them, table_name is the name of the table, column_name is the name of the column, data_type is the data type of the column, NOT NULL specifies that the column cannot be empty, and DEFAULT default_value specifies the default value of the column. For example, to create a table named cu

How to create a table using sql statement in mysql

How to create a table using SQL statements in MySQL

1. Basic syntax for creating a table

<code class="sql">CREATE TABLE table_name (
  column_name data_type [NOT NULL] [DEFAULT default_value],
  ...
);</code>
  • table_name:The name of the table to be created.
  • column_name: The name of the column.
  • data_type: The data type of the column, such as INT, VARCHAR, DATE, etc.
  • NOT NULL: The specified column cannot be NULL (null value).
  • DEFAULT default_value: Specifies the default value of the column. If not specified, it defaults to NULL.

2. Example

Suppose you want to create a table named "customers" containing the following columns:

  • id : INT, primary key, cannot be NULL
  • name: VARCHAR(255), cannot be NULL
  • email: VARCHAR(255), can be NULL, the default value is the empty string
  • phone_number: VARCHAR(255), can be NULL, no default value

You can use the following SQL statement to create the table:

<code class="sql">CREATE TABLE customers (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) DEFAULT '',
  phone_number VARCHAR(255)
);</code>

3. Other notes Note

  • Table names and column names are case-sensitive.
  • The structure of each table must be unique, there cannot be two columns with the same column name.
  • The primary key column must identify each record in the table and cannot contain NULL values.
  • The default value can be a constant, expression or subquery.
  • After you create a table, you can later use the ALTER TABLE statement to add, delete, or modify columns.

The above is the detailed content of How to create a table using sql statement 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