Question copied to clipboard successfully!

Common E-Commerce Database Schema

Reference this table structure and sample data to solve all 15 practice questions.

customers

Stores registered user details and loyalty status.

customer_id (PK)
name, email, city, created_at

products

Stores catalog items, pricing, and current inventory levels.

product_id (PK)
product_name, category, price, stock_qty

orders & audit

Tracks purchases and audit logging for deleted orders.

orders (order_id, customer_id, product_id, quantity, total_price, order_date)
order_audit (log_id, order_id, action_type, deleted_at)
-- Create Database
CREATE DATABASE IF NOT EXISTS ecommerce_db;
USE ecommerce_db;

-- Drop existing tables in reverse order of dependencies
DROP TABLE IF EXISTS order_audit;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS customers;

-- 1. Customers Table
CREATE TABLE customers (
    customer_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    city VARCHAR(50) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 2. Products Table
CREATE TABLE products (
    product_id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    stock_qty INT NOT NULL
);

-- 3. Orders Table
CREATE TABLE orders (
    order_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT,
    product_id INT,
    quantity INT NOT NULL,
    total_price DECIMAL(10,2) NOT NULL,
    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products(product_id) ON DELETE CASCADE
);

-- 4. Order Audit Table (Used for triggers)
CREATE TABLE order_audit (
    log_id INT AUTO_INCREMENT PRIMARY KEY,
    order_id INT,
    action_type VARCHAR(50),
    deleted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert Sample Data into Customers
INSERT INTO customers (name, email, city) VALUES
('Alice Smith', 'alice@example.com', 'New York'),
('Bob Jones', 'bob@example.com', 'Chicago'),
('Charlie Brown', 'charlie@example.com', 'Los Angeles'),
('Diana Prince', 'diana@example.com', 'New York'),
('Evan Wright', 'evan@example.com', 'Houston');

-- Insert Sample Data into Products
INSERT INTO products (product_name, category, price, stock_qty) VALUES
('Wireless Mouse', 'Electronics', 25.99, 150),
('Mechanical Keyboard', 'Electronics', 79.99, 80),
('Running Shoes', 'Sports', 59.99, 45),
('Yoga Mat', 'Sports', 19.99, 200),
('Coffee Maker', 'Home', 49.99, 30);

-- Insert Sample Data into Orders
INSERT INTO orders (customer_id, product_id, quantity, total_price) VALUES
(1, 1, 2, 51.98),
(2, 3, 1, 59.99),
(3, 2, 1, 79.99),
(1, 4, 3, 59.97),
(4, 5, 1, 49.99);