Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL CREATE TABLE Statement

The `CREATE TABLE` statement in MySQL is used to define a new table in the database. It specifies the table name, columns, and their data types, along with any constraints.

Usage

The `CREATE TABLE` statement is used when you need to set up a new table structure in your database to store data. It is an essential part of database schema design.

CREATE TABLE table_name (
    column1_name column1_datatype [constraints],
    column2_name column2_datatype [constraints],
    ...
);

In this syntax, `table_name` is the name of the new table, and each column is defined by its name, datatype, and optional constraints.

Examples

1. Basic Table Creation

CREATE TABLE students (
    id INT,
    name VARCHAR(100)
);

This example creates a simple `students` table with two columns: an integer `id` and a string `name` of up to 100 characters.

2. Table with Constraints

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    email VARCHAR(255) UNIQUE
);

Here, the `employees` table is created with a primary key constraint on `employee_id` and a unique constraint on `email` to ensure data integrity.

3. Table with Foreign Key

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    order_date DATE,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

This example creates an `orders` table with a foreign key constraint, linking `customer_id` to the `customer_id` column in the `customers` table for relational integrity.

4. Table with Default Values and AUTO_INCREMENT

CREATE TABLE products (
    product_id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) DEFAULT 0.00
);

This example demonstrates the use of `AUTO_INCREMENT` for `product_id` to automatically generate unique identifiers, and a default value of `0.00` for the `price` column.

Tips and Best Practices

  • Plan your schema. Carefully plan your table structure and relationships before creating tables to ensure efficient data retrieval and storage.
  • Use meaningful names. Choose clear and descriptive names for tables and columns to improve readability and maintainability.
  • Define constraints. Use constraints (e.g., `PRIMARY KEY`, `UNIQUE`, `FOREIGN KEY`) to enforce data integrity and prevent invalid data entry. Constraints are rules applied to columns to maintain accuracy and reliability of data.
  • Consider data types. Choose data types carefully for performance optimization. Large VARCHAR lengths can impact storage, so use appropriate lengths based on the expected data size.
  • Consider indexing. Create indexes on columns that are frequently used in search conditions to improve query performance.
  • Normalize data. Follow normalization principles to reduce data redundancy and improve database efficiency.