The CREATE TABLE statement is used to create a new table in a database. A table is a collection of related data organized in rows and columns.
Syntax
CREATE TABLE table_name (
column1 datatype [constraint],
column2 datatype [constraint],
...
);
Explanation
- table_name – The name of the table you want to create.
- column1, column2, … – Names of the columns in the table.
- datatype – Type of data the column can hold (e.g., INT, VARCHAR, DATE).
- constraint – Optional rules for the column, such as PRIMARY KEY, NOT NULL, UNIQUE.
Common Data Types
- INT – Whole numbers
- VARCHAR(size) – Text with a maximum length
- DATE – Date values
- FLOAT – Decimal numbers
Common Constraints
- PRIMARY KEY – Uniquely identifies each row
- NOT NULL – Ensures the column cannot have empty values
- UNIQUE – Ensures all values in the column are unique
- FOREIGN KEY – Links a column to a column in another table
Example
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
BirthDate DATE,
Email VARCHAR(100) UNIQUE
);
Explanation of Example
- StudentID – Integer column and primary key
- FirstName and LastName – Text columns that cannot be empty
- BirthDate – Stores the student’s date of birth
- Email – Stores student email and must be unique