MySQL : CREATE TABLE Statement

The `CREATE TABLE` statement in MySQL is used to create a new table in a specified database. Here's the basic syntax:


CREATE TABLE table_name (
    column1 datatype [optional_constraints],
    column2 datatype [optional_constraints],
    ...
);

 

  • table_name is the name of the table you want to create.
  • column1, column2, etc. are the names of the columns in the table.
  • datatype specifies the data type of each column.
  • [optional_constraints] define constraints such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, etc.

For example, let's create a simple table named users with columns for user_id, username, and email:


CREATE TABLE users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE
);

 

This statement creates a table named users with three columns: user_id as an integer auto-incrementing primary key, username as a variable character string of maximum length 50 and cannot be NULL, and email as a variable character string of maximum length 100 and must be unique.

You can also specify additional constraints like DEFAULT, CHECK, and REFERENCES for more complex requirements. Additionally, you may need appropriate privileges to create a table, depending on your MySQL user permissions.