The CREATE TABLE statement is a fundamental SQL command used to create new tables in a database. It defines the structure of a table, including its columns, data types, and constraints.
The basic syntax for creating a table in SQL is as follows:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...
);
Let's create a basic "employees" table:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
hire_date DATE
);
This example demonstrates the creation of a table with various column types and constraints.
Constraints are rules enforced on the data columns in a table. They are crucial for maintaining data integrity. Common constraints include:
Here's an example of a "orders" table with various constraints:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATE DEFAULT CURRENT_DATE,
total_amount DECIMAL(10, 2) CHECK (total_amount > 0),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
When creating tables, keep these points in mind:
Understanding the CREATE TABLE statement is crucial for effective SQL schema design. It forms the foundation of your database structure and plays a vital role in overall database performance and maintainability.