Advertisement
Google Ad Slot: content-top
MySQL Create Table
MySQL CREATE TABLE Statement
The CREATE TABLE statement in MySQL is used to define a new table within a database, specifying column names, data types, and constraints.
Syntax
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 likePRIMARY 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).
Check All Tables in a Database
SHOW TABLES;
View Table Structure
DESC students;
MySQL CREATE TABLE Using Another Table
In MySQL, you can create a new table using the structure or data from an existing table.
1. Create a Table with the Same Structure (Without Data)
To create a new table with the same structure as an existing table without copying data, use:
CREATE TABLE new_table LIKE existing_table;
- This creates
students_backupwith the same columns and data types asstudentsbut without any data.
2. Create a Table and Copy Data from Another Table
To create a table and copy data from an existing table:
Syntax:
CREATE TABLE new_table AS SELECT * FROM existing_table;
- This creates
students_copywith the same structure and all data fromstudents.
3. Copy Specific Columns from Another Table
To copy only specific columns into the new table:
- This creates
new_studentswith onlystudent_idandnamefromstudents.
4, Copy Data with a Condition
To copy only specific rows into the new table:
- This creates
adult_studentscontaining only students 18 years or older.
Key Differences Between LIKE & AS SELECT
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.