The CREATE TABLE
statement in SQL Server database is used to create a new table in a database.
CREATE TABLE syntax
The basic syntax for creating a table is as follows:
CREATE TABLE table_name
(
column_name_1 datatype constraint,
column_name_2 datatype constraint,
....
column_name_n datatype constraint,
PRIMARY KEY (column1, column2, ... column_n)
);
table_name
is the name of the table you want to create.
column_name_1, column_name_2, ... column_name_n
are the names of the columns in the table.
datatype
is the data type for each column, such as INT
, VARCHAR
, DATE
, etc.
constraint
is an optional constraint for each column, such as NOT NULL
, UNIQUE
, or FOREIGN KEY
.
PRIMARY KEY
is a constraint that specifies a unique identifier for each row in the table.
CREATE TABLE example
For example, the following SQL creates a table named "employees" with four columns: "id" (INT, primary key), "name" (VARCHAR), "age" (INT), and "salary" (DECIMAL).
CREATE TABLE employees
(
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
salary DECIMAL(10, 2) NOT NULL
);
It's also possible to create a table from the result of a SELECT statement.
SELECT * INTO new_Students FROM Students;