SQL CREATE TABLE

SQL CREATE TABLE

This tutorial will explain how to create table in SQL and how to use them with the examples.

A table is a array of data stored in a database. A table consists of columns and rows. To create a new table, you use the CREATE TABLE statement with the following syntax:


CREATE TABLE table_name(
column_name_1 data_type default value column_constraint,
column_name_2 data_type default value column_constraint,
...,
table_constraint
);

In order to create a table we will need a name and also a column.

Lets create a sample table work on it
CREATE TABLE Customers (
FullName VARCHAR(50) NOT NULL
);

Table name must be unique within the database. Trying to create a table with a name already exists, it will fail with an error. As an example if you run the following code, it will fail on second "Create Table" statement as table1 has been created on the first statement.

CREATE TABLE Table1 (
Column1 VARCHAR(50) NOT NULL
);

CREATE TABLE Table1 (
Column2 VARCHAR(50) NOT NULL
);


You can create multiple columns on Create Table statement with a comma-separated

CREATE TABLE Table2 (
Column1 VARCHAR(50) NOT NULL,
Column2 VARCHAR(50) NOT NULL
);

You can create columns with different data types. The word after column name defines its data type

CREATE TABLE Table3 (
Column1 VARCHAR(50) NOT NULL,
Column2 INT NOT NULL
);


The default value and column constraints written after data type of the column. In the following example NOT NULL is the constraint which ensures NULL value cannot be entered into Column1 field

CREATE TABLE Table3 (
Column1 VARCHAR(50) NOT NULL
);

The following example defines Column1 as primary key of Table4. This makes Column1 values unique in Table4. On duplicated value entries, it will fail

CREATE TABLE Table4 (
Column1 VARCHAR(50) NOT NULL,
CONSTRAINT PK_Table4 PRIMARY KEY (Column1)
);