The CREATE TABLE statement in SQL is used to define a new table in a database. It includes the table's name and the definitions for its columns, including the data types, constraints, and any other necessary properties.
Here’s the basic syntax for a CREATE TABLE statement:
CREATE TABLE table_name (
column1 datatype [constraint],
column2 datatype [constraint],
column3 datatype [constraint],
...
[table_constraints]
);
Example:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
HireDate DATE,
Salary DECIMAL(10, 2),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
Explanation:
EmployeeID INT PRIMARY KEY: Creates a columnEmployeeIDof typeINTand sets it as the primary key.FirstName VARCHAR(50): Creates a columnFirstNameof typeVARCHARwith a maximum length of 50 characters.HireDate DATE: Creates a columnHireDatewith theDATEtype.Salary DECIMAL(10, 2): Creates a columnSalarywith theDECIMALtype, allowing up to 10 digits, with 2 digits after the decimal point.DepartmentID INT: Creates a columnDepartmentIDof typeINT.FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID): Establishes a foreign key constraint onDepartmentIDthat references theDepartmentIDcolumn in theDepartmentstable.
You can add various constraints such as NOT NULL, UNIQUE, CHECK, etc., to control the data that can be inserted into the table.
No comments:
Post a Comment