Designing a schema in MySQL involves planning tables, columns, keys, and relationships, then implementing them with CREATE statements.
Designing a schema means translating business entities into MySQL objects—databases, tables, columns, indexes, and constraints—so data stays organized, accurate, and fast to query.
Issue a CREATE DATABASE
statement, then switch to it with USE
.Keep names short, lowercase, and without spaces.
CREATE DATABASE ecommerce;
USE ecommerce;
Start with core entities: Customers, Products, Orders, and OrderItems.Model one-to-many links with foreign keys so deletes or updates cascade safely.
Create each table with primary keys, appropriate data types, NOT NULL constraints, default values, and indexes that support common queries.
CREATE TABLE Customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);.
CREATE TABLE Products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL,
price DECIMAL(10,2) NOT NULL,
stock INT DEFAULT 0
);
CREATE TABLE Orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
total_amount DECIMAL(10,2) NOT NULL,
FOREIGN KEY (customer_id) REFERENCES Customers(id)
ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE TABLE OrderItems (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
FOREIGN KEY (order_id) REFERENCES Orders(id)
ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES Products(id)
);
Use foreign keys, UNIQUE constraints, CHECK constraints (MySQL 8+), and proper data types.Add indexes for JOIN columns and frequently filtered fields.
• Normalize until queries become cumbersome, then denormalize selectively.
• Prefer INT PKs with AUTO_INCREMENT.
• Use TIMESTAMP/DATETIME for events.
• Document every table and column.
• Run EXPLAIN
on critical queries and add composite indexes as needed.
.
Yes. In MySQL, the terms are interchangeable; CREATE SCHEMA
is an alias for CREATE DATABASE
.
Normalize to third normal form first. Denormalize only when profiling shows clear performance gains.
MySQL lacks RENAME DATABASE
. Create a new database, migrate objects, update app configs, then drop the old database.