MSDN Archive

CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database. It defines the table's name, its columns, and the data types for each column.

Syntax

The basic syntax for the CREATE TABLE statement is:

CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    column3 datatype constraints,
    ....
);

Parameters

Examples

1. Creating a simple table:

This example creates a table named Customers with an ID, name, and email.

CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(100) UNIQUE
);

2. Creating a table with a foreign key:

This example creates an Orders table that references the Customers table using a foreign key.

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    OrderDate DATE,
    TotalAmount DECIMAL(10, 2),
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

3. Creating a table with a CHECK constraint:

This example creates a Products table where the price must be greater than or equal to zero.

CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    ProductName VARCHAR(100) NOT NULL,
    Price DECIMAL(10, 2) CHECK (Price >= 0)
);

Important Considerations:

  • Data Types: Choosing the correct data type for each column is crucial for performance and data integrity.
  • Primary Keys: Every table should ideally have a primary key to uniquely identify its rows.
  • Indexes: Consider adding indexes to columns that are frequently used in WHERE clauses or JOIN conditions to improve query performance.
  • Constraints: Use constraints judiciously to maintain data accuracy and enforce business rules.
  • Database Specific Syntax: While the core syntax is standard SQL, specific database systems (like SQL Server, MySQL, PostgreSQL, Oracle) might have minor variations or additional features. Always refer to the documentation for your specific database.