1 CREATE
TopThe CREATE command builds new database objects. We'll use it throughout all 5 topics in this chapter, building an employees table step by step.
CREATE DATABASE
CREATE DATABASE company_db;
USE company_db;CREATE TABLE with Constraints
Here's a real-world table with all the important data types and constraints:
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) UNIQUE NOT NULL,
department VARCHAR(50) DEFAULT 'General',
salary DECIMAL(10,2) CHECK (salary > 0),
hire_date DATE NOT NULL,
is_active BOOLEAN DEFAULT TRUE
);Understanding Constraints
| Constraint | What It Does | Example |
|---|---|---|
PRIMARY KEY | Uniquely identifies each row, cannot be NULL | id INT PRIMARY KEY |
NOT NULL | Column must have a value | name VARCHAR(100) NOT NULL |
UNIQUE | No duplicate values allowed | email VARCHAR(150) UNIQUE |
DEFAULT | Sets a value if none is provided | department DEFAULT 'General' |
CHECK | Validates data against a condition | CHECK (salary > 0) |
FOREIGN KEY | Links to another table's primary key | FOREIGN KEY (dept_id) REFERENCES departments(id) |
AUTO_INCREMENT | Automatically generates sequential IDs | id INT AUTO_INCREMENT |
Think of it this way: CREATE TABLE is like designing a spreadsheet template — you define the column headers and rules before any data goes in. Once created, the table enforces those rules on every row you INSERT.
Key Takeaways
-
CREATE DATABASEmakes a new database;CREATE TABLEmakes a new table - Always define a
PRIMARY KEY— it uniquely identifies each row - Use constraints (
NOT NULL,UNIQUE,CHECK) to enforce data quality at the database level -
AUTO_INCREMENTgenerates IDs automatically so you don't have to