MySQL • DDL • Structure Management
Database tables have a lifecycle: they are defined, used to store data, and eventually removed.
PRIMARY KEY, UNIQUE) that ensure data integrity.Use this statement to define a new container for your data.
-- Syntax Template
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
);
-- Real Example: Creating a Users table
CREATE TABLE Users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
INT / BIGINT: Whole numbers (IDs, counts).VARCHAR(n): Variable text up to n characters (names, emails).DATE / DATETIME: Time-based data.DECIMAL(10,2): Exact money values.
-- Parent Table
CREATE TABLE Departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);
-- Child Table with Foreign Key
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES Departments(dept_id)
);
Use this statement to permanently delete a table. This is often done during cleanup or restructuring.
DROP TABLE cannot be undone. All rows, indexes, and structure are lost immediately.
-- Basic Drop (Will error if table doesn't exist)
DROP TABLE Users;
-- Safe Drop (Prevents error if table is missing)
DROP TABLE IF EXISTS Users;
-- Drop Multiple Tables at once
DROP TABLE Employees, Departments;
This flow demonstrates creating a table, using it, and then cleaning it up.
-- 1. DEFINE: Create a temporary log table
CREATE TABLE AppLogs (
log_id INT AUTO_INCREMENT PRIMARY KEY,
message TEXT,
level VARCHAR(10) DEFAULT 'INFO'
);
-- 2. USE: Insert data into the structure
INSERT INTO AppLogs (message, level)
VALUES ('System started', 'INFO'), ('Connection failed', 'ERROR');
-- 3. VERIFY: Check the data
SELECT * FROM AppLogs;
-- 4. CLEANUP: Remove the table completely
DROP TABLE AppLogs;
Customers, not Cust).PRIMARY KEY for every table to uniquely identify rows.mysqldump) before running DROP commands in production.DROP TABLE IF EXISTS at the start of setup scripts to ensure a clean slate before creating tables.Products with columns for id, name, and price.DROP TABLE Products; and verify it is gone using SHOW TABLES;.