MySQL Tutorial
The CREATE TABLE statement in MySQL is used to define a new table within a database, specifying column names, data types, and constraints.
CREATE TABLE table_name ( column1 datatype constraints, column2 datatype constraints, ... );
table_name: Name of the table.column1, column2, ...: Column names.datatype: Defines the type of data (e.g., INT, VARCHAR, DATE).constraints: Rules like PRIMARY KEY, NOT NULL, UNIQUE, etc.✅ student_id is an AUTO_INCREMENT PRIMARY KEY (unique ID for each student).
✅ name cannot be NULL (NOT NULL).
✅ age must be 18 or older (CHECK (age >= 18)).
✅ email must be unique (UNIQUE).
✅ enrollment_date defaults to current date (DEFAULT CURRENT_DATE).
SHOW TABLES;
DESC students;
In MySQL, you can create a new table using the structure or data from an existing table.
To create a new table with the same structure as an existing table without copying data, use:
CREATE TABLE new_table LIKE existing_table;
students_backup with the same columns and data types as students but without any data.To create a table and copy data from an existing table:
CREATE TABLE new_table AS SELECT * FROM existing_table;
students_copy with the same structure and all data from students.To copy only specific columns into the new table:
new_students with only student_id and name from students.To copy only specific rows into the new table:
adult_students containing only students 18 years or older.|
Method |
Copies Structure |
Copies Data |
Copies Constraints (e.g., PRIMARY KEY, AUTO_INCREMENT) |
|---|---|---|---|
|
CREATE TABLE new_table LIKE existing_table; |
✅ Yes |
❌ No |
✅ Yes |
|
CREATE TABLE new_table AS SELECT * FROM existing_table; |
✅ Yes |
✅ Yes |
❌ No |
Note
✔ Use LIKE when you only want the structure.
✔ Use AS SELECT when you need both structure and data but without constraints.