Wednesday, December 18, 2024

SQL CREATE TABLE Statement

 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 column EmployeeID of type INT and sets it as the primary key.
  • FirstName VARCHAR(50): Creates a column FirstName of type VARCHAR with a maximum length of 50 characters.
  • HireDate DATE: Creates a column HireDate with the DATE type.
  • Salary DECIMAL(10, 2): Creates a column Salary with the DECIMAL type, allowing up to 10 digits, with 2 digits after the decimal point.
  • DepartmentID INT: Creates a column DepartmentID of type INT.
  • FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID): Establishes a foreign key constraint on DepartmentID that references the DepartmentID column in the Departments table.

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