The CREATE TABLE
statement is used in SQL to define a new table and its columns. When creating a table, you must specify the column names, data types, and optionally, constraints like primary keys or default values.
SQL Create Table Syntax
SQL
x
1
CREATE TABLE table_name (
2
column1 datatype constraint,
3
column2 datatype constraint,
4
...
5
);
SQL Create Table Using Another Table
Sometimes, you might want to create a new table based on an existing one, either copying just its structure or both its structure and data.
This query creates a new table with the same structure as an existing one, but without copying any data.
SQL
1
1
CREATE TABLE new_table
2
AS
3
SELECT * FROM existing_table
4
WHERE 1 = 0;
This query creates a new table and also copies all the data from the existing one. This approach is useful for backups, testing, or creating archive tables.
SQL
1
1
CREATE TABLE new_table
2
AS
3
SELECT * FROM existing_table;
SQL Create Table Example
This command creates a table named Students
with several useful fields.
SQL
1
1
CREATE TABLE Drivers (
2
DriversID INT PRIMARY KEY,
3
FirstName VARCHAR(50) NOT NULL,
4
LastName VARCHAR(50),
5
BirthDate DATE,
6
RegistrationYear INT DEFAULT 2023
7
);
