Syntax for Creating a Table
-
table_name
: The name of your table. -
column1, column2, ...
: Names of the table columns. -
datatype
: The type of data the column will store (e.g.,INT
,VARCHAR
,TEXT
,DATE
). -
constraints
: Rules applied to columns (e.g.,PRIMARY KEY
,NOT NULL
,AUTO_INCREMENT
).
Example: Creating a Users Table
Explanation:
-
id INT AUTO_INCREMENT PRIMARY KEY
→ Creates a uniqueid
that increments automatically. -
name VARCHAR(100) NOT NULL
→ Stores the user's name with a maximum of 100 characters and ensures it is not empty. -
email VARCHAR(150) UNIQUE NOT NULL
→ Stores email addresses, must be unique, and cannot be empty. -
password VARCHAR(255) NOT NULL
→ Stores hashed passwords. -
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
→ Automatically sets the current date and time when a record is created.
Additional Constraints and Features
1. Foreign Key Example
If you want to link another table (e.g., orders
) to the users
table:
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
→ Ensures that when a user is deleted, all their orders are also deleted.
2. Adding Default Values
-
DECIMAL(10,2)
→ Stores prices with two decimal places. -
DEFAULT
→ Sets default values forprice
andstock
.
3. Enum for Limited Options
-
ENUM('Admin', 'Manager', 'Employee')
→ Restricts therole
column to only accept these values.
Checking Table Structure
To see the structure of a table:
Modifying an Existing Table
1. Add a New Column
2. Modify an Existing Column
3. Remove a Column
Deleting a Table
To delete a table permanently: