MSDN Logo

MSDN Documentation

CREATE TABLE

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 type for each column.

Basic Syntax

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

Parameters

Example: Creating a Simple 'Customers' Table

This example creates a table named 'Customers' with columns for customer ID, first name, last name, and email.

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

Explanation of the Example:

Example: Creating a 'Products' Table with a Foreign Key

This example demonstrates creating a 'Products' table that references a 'Categories' table using a foreign key.

CREATE TABLE Products (
    ProductID INT PRIMARY KEY AUTO_INCREMENT,
    ProductName VARCHAR(100) NOT NULL,
    CategoryID INT,
    Price DECIMAL(10, 2),
    FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID)
);
Before creating the Products table, you would need to create the Categories table:
CREATE TABLE Categories (
    CategoryID INT PRIMARY KEY AUTO_INCREMENT,
    CategoryName VARCHAR(50) NOT NULL
);

Common Data Types

Type Description
INT Integer numbers.
VARCHAR(n) Variable-length character string, up to n characters.
CHAR(n) Fixed-length character string, n characters long.
TEXT Longer strings.
DATE Stores date values (YYYY-MM-DD).
DATETIME Stores date and time values (YYYY-MM-DD HH:MM:SS).
DECIMAL(p, s) Exact numeric value with p total digits and s digits after the decimal point.
FLOAT Approximate floating-point number.
BOOLEAN Stores TRUE or FALSE values.

Common Constraints

Constraint Description
PRIMARY KEY Uniquely identifies each record in a table. Cannot contain NULL values.
FOREIGN KEY Uniquely identifies a record in another table. It's a link between two tables.
UNIQUE Ensures all values in a column are different. Can contain one NULL value.
NOT NULL Ensures that a column cannot have a NULL value.
CHECK Ensures that all values in a column satisfy a specific condition.
DEFAULT value Sets a default value for a column if no value is specified.
AUTO_INCREMENT Automatically assigns an incremental value to a column when a new record is inserted (typically for primary keys).
Note on Database Systems: The exact syntax for AUTO_INCREMENT (e.g., IDENTITY in SQL Server, SERIAL in PostgreSQL) and some data types might vary slightly between different SQL database systems (like MySQL, PostgreSQL, SQL Server, Oracle). Always consult the specific documentation for your RDBMS.