To create a table in MySQL, you use the CREATE TABLE statement. Here’s the basic syntax:
CREATE TABLE table_name (
column1_name column1_datatype constraints,
column2_name column2_datatype constraints,
...
);
Example -
Here’s a real-world example to create a simple employees table:
CREATE TABLE employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
hire_date DATE NOT NULL,
salary DECIMAL(10, 2)
);
Explanation:
INT, VARCHAR, DATE, DECIMAL are data types.
AUTO_INCREMENT automatically generates a new ID for each row.
PRIMARY KEY uniquely identifies each row.
NOT NULL ensures the column must have a value.
UNIQUE ensures no duplicate values in the column.
Creating with Foreign Key Example -
If you want to create a table with a foreign key (say linking employees to departments):
CREATE TABLE departments (
department_id INT AUTO_INCREMENT PRIMARY KEY,
department_name VARCHAR(100) NOT NULL
);
CREATE TABLE employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
- Log in to post comments