SQL CREATE TABLE Statement

tags: #sql/basic_statements

Initializing a table in a database

The CREATE TABLE statement is used to create a new table in a database. Contents of the relation and the relation itself are stored as files by the DBMS (known as "base relations").

Syntax:

CREATE TABLE table_name(
	column1 datatype constraint, // e.g. NOT NULL
	column2 datatype constraint, // can list more than 1 constraint
	column3 datatype constraint1 constraint2 ...,
	...
)

Alternatively, we can also specify the schema (or database), in which we want to create the table object:

CREATE TABLE dbName.tableName (
	column1 datatype constraint,
	...
)

Example:

CREATE TABLE Persons (
    PersonID int NOT NULL,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255) 
);

Creating a new table from existing table

A copy of an existing table can also be created using CREATE TABLE.

The new table gets the same column definitions.

All columns or specific columns can be selected.

Copied Data

If you create a new table using an existing table, the new table will be filled with the existing values from the old table.

Selecting all columns
CREATE TABLE new_table_name AS
    SELECT * FROM existing_table_name
    WHERE ....
Selecting specific columns
CREATE TABLE new_table_name AS
    SELECT column1, column2,...
    FROM existing_table_name
    WHERE ....;
Powered by Forestry.md