AI Reading
Quick summary of this article
Chapter 2: Schema Design, Data Types & Table Creation
AI Reading
Quick summary of Chapter 2
A well-architected database schema is the foundation of high-performance software. In this chapter, you will master MySQL data types, understand relational constraints, and create normalized parent and child tables with foreign key integrity.
- Data Type Selection: Choose optimal storage formats across INTEGER, VARCHAR, DATE, and DECIMAL types.
- Table Constraints: Enforce business logic with PRIMARY KEY, FOREIGN KEY, NOT NULL, and UNIQUE rules.
- ERD Modeling: Design an Entity-Relationship Diagram connecting parent Departments to child Employees.
- Foreign Key Cascading: Understand the consequences of referential actions (RESTRICT, CASCADE, SET NULL).
- Table Verification: Inspect table structures, index maps, and column properties with DESCRIBE and SHOW CREATE TABLE.
Welcome to Chapter 2. In software engineering, your application’s speed, data consistency, and long-term maintainability depend heavily on good Schema Design. A poorly chosen data type or missing foreign key index can lead to data corruption, orphaned records, and catastrophic performance slowdowns as your data grows.
In this chapter, we will examine the core MySQL data types, understand the role of relational constraints, and write production-grade Data Definition Language (DDL) statements to construct our corporate departments and employees tables.
🧩 2.1 Essential MySQL Data Types
Selecting the smallest data type that can safely accommodate all possible future values minimizes disk storage, accelerates index lookups, and maximizes RAM caching in the MySQL Buffer Pool.
| Data Type | Storage Bytes | Value Range / Capacity | Best Practice Use Case |
|---|---|---|---|
TINYINT |
1 byte | -128 to 127 (or 0 to 255 unsigned) | Status flags, age, booleans (0 or 1) |
INTEGER (or INT) |
4 bytes | -2.14 Billion to +2.14 Billion | Entity IDs, foreign keys, quantities |
BIGINT |
8 bytes | -9.22 Quintillion to +9.22 Quintillion | High-volume transaction IDs, analytics events |
VARCHAR(N) |
1-2 bytes + text | Variable length up to N characters | Names, email addresses, titles, phone numbers |
CHAR(N) |
N bytes fixed | Fixed length; padded with spaces | Fixed codes (e.g. ISO Country codes like ‘US’, ‘IN’) |
DATE |
3 bytes | 1000-01-01 to 9999-12-31 |
Calendar dates: hire date, birth date, invoice date |
DECIMAL(M, D) |
Variable | Exact precision: M total digits, D decimals | Currency, financial transactions (avoids float rounding errors) |
🛡️ 2.2 Table Constraints & Data Integrity
Constraints are rules enforced by the database engine on table columns to prevent invalid data entry:
PRIMARY KEY: Uniquely identifies each row. Automatically creates an underlying unique clustered B-Tree index and rejectsNULLvalues.FOREIGN KEY: Ensures referential integrity by establishing that a value in the child table must already exist in the referenced parent table.NOT NULL: Mandates that the column must contain a valid value when a new row is inserted.UNIQUE: Guarantees that all values in that column are distinct from one another.DEFAULT: Provides a fallback value if none is specified during an insert.
💾 2.3 Designing the Corporate Schema (ERD)
We model an organizational structure containing Departments and Employees. An employee belongs to one department, while a department can employ multiple employees (a 1-to-Many relationship):
+----------------------+ +-----------------------+
| DEPARTMENTS | | EMPLOYEES |
+----------------------+ +-----------------------+
| * department_id (PK) |<----+ | * employee_id (PK) |
| department_name | | | first_name |
| location_id | | | last_name |
+----------------------+ | | email |
| | phone_number |
| | hire_date |
| | job_id |
| | salary |
| | commission_pct |
| | manager_id (Self-FK)|
+-------| department_id (FK) |
+-----------------------+
✅ 2.4 Creating the Parent Table: departments
Because child tables reference parent tables, the parent table must be created first:
-- Create parent table: departments
CREATE TABLE departments (
department_id INTEGER PRIMARY KEY,
department_name VARCHAR(30) NOT NULL,
location_id INTEGER
);
👥 2.5 Creating the Child Table: employees
The employees table defines two crucial constraints: a Foreign Key pointing to departments(department_id), and a self-referencing relationship where manager_id refers to another employee’s employee_id:
-- Create child table: employees
CREATE TABLE employees (
employee_id INTEGER,
first_name VARCHAR(20),
last_name VARCHAR(25) NOT NULL,
email VARCHAR(25) NOT NULL,
phone_number VARCHAR(20),
hire_date DATE NOT NULL,
job_id VARCHAR(10) NOT NULL,
salary INTEGER NOT NULL,
commission_pct INTEGER,
manager_id INTEGER,
department_id INTEGER,
CONSTRAINT pk_emp PRIMARY KEY (employee_id),
CONSTRAINT fk_deptno FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
🔍 2.6 Verifying Schema Structure
After creating tables, use the following commands to inspect the schema metadata:
-- Inspect columns, types, nullability, and keys
DESCRIBE employees;
-- View the exact SQL definition including engines and constraints
SHOW CREATE TABLE employees\G
⚠ 2.7 Production Tips & Common Mistakes
- Always Index Foreign Keys: While MySQL automatically creates an index for foreign keys, ensure that any column frequently used in
JOIN ... ONconditions is indexed to avoid full table scans. - Avoid Floating Point for Money: Never use
FLOATorDOUBLEto store monetary values like salaries or prices. Floating-point numbers use binary approximations that cause rounding errors (e.g. 0.1 + 0.2 = 0.30000000000000004). Always useDECIMAL(10,2).
❓ Frequently Asked Questions (FAQ)
1. What happens if I try to delete a department that still has employees?
Because the foreign key constraint was defined without ON DELETE CASCADE, MySQL uses the default RESTRICT action and will throw Error 1451: Cannot delete or update a parent row: a foreign key constraint fails. This protects your database from orphaned employee records.
2. Can a Primary Key contain NULL values?
No. By SQL standard definition, a Primary Key must uniquely identify each row and cannot contain NULL.
