The CREATE TABLE
statement in SQL is used to create a new table in a database. It defines the structure of the table, including the column names, data types, constraints, and indexes.
Here's a basic example of how to use the CREATE TABLE
statement:
CREATE TABLE TableName ( Column1Name DataType1, Column2Name DataType2, ... CONSTRAINT ConstraintName CONSTRAINT_TYPE (ConstraintCondition), ... );
Let's break down the components of the CREATE TABLE
statement:
TableName
: Specifies the name of the table you want to create.Column1Name
, Column2Name
, etc.: Define the names of the columns in the table.DataType1
, DataType2
, etc.: Specify the data types for each column.CONSTRAINT ConstraintName CONSTRAINT_TYPE (ConstraintCondition)
: Define constraints for the table. Constraints are optional and enforce rules on the data in the table. ConstraintName
is an optional identifier for the constraint. CONSTRAINT_TYPE
can be PRIMARY KEY
, FOREIGN KEY
, UNIQUE
, CHECK
, etc., depending on the type of constraint. ConstraintCondition
specifies the condition that the data must satisfy for the constraint to be valid.Here's a concrete example:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), Age INT CHECK (Age >= 18), DepartmentID INT, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) );
In this example:
Employees
has columns EmployeeID
, FirstName
, LastName
, Age
, and DepartmentID
.EmployeeID
is defined as the primary key.Age
column has a CHECK
constraint to ensure that the age is equal to or greater than 18.DepartmentID
is a foreign key referencing the DepartmentID
column in the Departments
table.This CREATE TABLE
statement creates a table named Employees
with the specified columns and constraints.