Lesson

MySQL CREATE TABLE

10 min reading
Free Course

MySQL CREATE TABLE: Defining Database Table Schemas

The MySQL CREATE TABLE statement creates a new table by defining its column names, data types, nullability rules, primary key, and indexes. Designing clean table definitions upfront prevents data corruption and avoids expensive schema rewrites later.

Basic Syntax

List each column with its type and constraints, then specify the PRIMARY KEY, indexes, and ENGINE=InnoDB DEFAULT CHARSET=utf8mb4:

CREATE TABLE IF NOT EXISTS table_name (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    column_name VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Practical SQL Example

This script creates demo_orders with an auto-increment primary key, exact decimal pricing, a foreign key reference to demo_customers, and a lookup index:

CREATE TABLE IF NOT EXISTS demo_orders (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    customer_id BIGINT UNSIGNED NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    total_amount DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_demo_orders_customer (customer_id),
    CONSTRAINT fk_demo_orders_customer
        FOREIGN KEY (customer_id) REFERENCES demo_customers(id)
        ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Common Mistakes and Best Practices

  • Always Specify ENGINE=InnoDB and utf8mb4: InnoDB gives you transactions, row-level locking, and foreign keys, while utf8mb4 supports full Unicode text.
  • Avoid FLOAT for Currency: Always choose DECIMAL(10, 2) (or integer cents) for money columns so totals never suffer binary floating-point rounding bugs.
  • Keep Columns NOT NULL by Default: Only allow NULL when a missing value carries genuine meaning, such as shipped_at on an unshipped order.

Frequently Asked Questions

Can I copy a table structure without copying its rows?

Yes, run CREATE TABLE demo_orders_copy LIKE demo_orders; to clone columns, primary keys, and indexes into an empty table.

What does IF NOT EXISTS do in CREATE TABLE?

It prevents MySQL from throwing an error if the table already exists, though it does not modify an existing table's columns if the schema differs.

Is INT or BIGINT better for primary keys?

Use BIGINT UNSIGNED (or INT UNSIGNED for small lookup tables) so high-traffic tables never exhaust the 2.1 billion signed INT limit.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum