T-SQL » Statements » CREATE TABLE

Syntax:
CREATE TABLE table_name
    ( column_name data_type [ ( size ) ] [ NULL | NOT NULL ]
    [ , column2_name data_type [ ( size ) ] [ NULL | NOT NULL ] [ , ... ] ]
    [ , CONSTRAINT multifieldindex [ , ... ] ] )
table_name
The parameter that designates the name of the table being created.
column_name
The parameter(s) that specifies the name(s) of the field(s) to be added to the table.
data_type
The parameter(s) that specifies the data type(s) of the newly added field(s).
NULL | NOT NULL
The constraint that indicates whether a field can or cannot contain a NULL value.
CONSTRAINT multifieldindex
Specifies any constraints on the newly created table.

The CREATE TABLE statement is used to create a new table and its fields.

Examples

Code:
CREATE TABLE Names (Name TEXT);
Output:
The command(s) completed successfully.
Explanation:

At its simplest you can create a table containing only a single field by specifying the name you want to give the table, the field name, and the type of data you want the field to contain.

Language(s): MS SQL Server
Code:
CREATE TABLE Names
(FirstName VARCHAR (20), LastName VARCHAR (20));
Output:
The command(s) completed successfully.
Explanation:

This example shows how to include more than one field, and also limit the size of those fields by stating the size in parentheses after the data type declaration.

Language(s): MS SQL Server
Code:
CREATE TABLE Names
(FirstName VARCHAR (20), LastName VARCHAR (20) NOT NULL);
Output:
The command(s) completed successfully.
Explanation:

By including the NOT NULL expression at the end of the declaration for a specific field, it can be required that this particular field always have valid data entered into it. However, if the data entered does not meet the requirements, a warning message will be displayed.

Language(s): MS SQL Server
Code:
CREATE TABLE Names
(FirstName VARCHAR (20), LastName VARCHAR (20), DateOfBirth DATETIME,
CONSTRAINT MultiConstraint UNIQUE(FirstName, LastName, DateOfBirth));
Output:
The command(s) completed successfully.
Explanation:

Restrictions can also be placed on the data, or combinations of data, that are to be entered. This can be accomplished using the CONSTRAINT clause. This example expands on the previous ones by adding a Date of Birth field and requiring that the combination of data in all three fields be unique. The multifieldindex must be a unique name within the database.

Language(s): MS SQL Server

See Also: