SQL CREATE TABLE Statement
The CREATE TABLE
statement in SQL is used to create new tables in a database. Tables are the fundamental structures for organizing and storing data.
CREATE TABLE: Definition and Usage
When you create a table, you define its name and the columns it will contain. For each column, you specify a data type that determines what kind of data it can hold (e.g., numbers, text, dates).
Syntax
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
...
);
table_name
is the name you choose for your new table. Each columnN datatype
line defines a column; columnN
is the column's name, and datatype
specifies the type of data it will store (e.g., INT
, VARCHAR(255)
, DATE
). For more information on data types see the Data Types Reference.
Examples
Creating a New Table
This example creates a table named "Persons" with five columns: PersonID, LastName, FirstName, Address, and City.
Syntax
CREATE TABLE Persons (
PersonID INT,
LastName VARCHAR(255),
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255)
);
Output
A new, empty table named "Persons" is created. It has five columns with the specified data types. You can then use INSERT INTO
statements to add data to this table.
PersonID | LastName | FirstName | Address | City |
---|
Creating a Table from an Existing Table
You can create a new table by copying data from an existing table using a SELECT
statement. This is useful for making a copy of a table or creating a new table containing only certain columns from the original table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2, ...
FROM existing_table_name
WHERE condition;
Example: Copying Data from Customers to TestTable
Syntax
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
Output
Creates a new table named "TestTable" with columns 'customername' and 'contactname', populated with data from the 'customers' table.
customername | contactname |
---|