This Oracle tutorial explains how to use the Oracle CREATE TABLE statement with syntax, examples, and practice exercises.
The Oracle CREATE TABLE statement allows you to create and define a table.
The syntax for the CREATE TABLE statement in Oracle/PLSQL is:
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
column_n datatype [ NULL | NOT NULL ]
);
The name of the table that you wish to create.
The columns that you wish to create in the table. Each column must have a datatype. The column should either be defined as "null" or "not null" and if this value is left blank, the database assumes "null" as the default.
Let's look at an Oracle CREATE TABLE example.
CREATE TABLE customers
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
This Oracle CREATE TABLE example creates a table called customers which has 3 columns.
Now the only problem with this Oracle CREATE TABLE statement is that you have not defined a primary key for the table. We could modify this CREATE TABLE statement and define the customer_id as the primary key as follows:
CREATE TABLE customers
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
Create an Oracle table called suppliers that stores supplier ID, name, and address information.
The Oracle CREATE TABLE statement for the suppliers table is:
CREATE TABLE suppliers
( supplier_id number(10) NOT NULL,
supplier_name varchar2(50) NOT NULL,
address varchar2(50),
city varchar2(50),
state varchar2(25),
zip_code varchar2(10)
);
Create an Oracle table called customers that stores customer ID, name, and address information.
But this time, the customer ID should be the primary key for the table.
The Oracle CREATE TABLE statement for the customers table is:
CREATE TABLE customers
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
address varchar2(50),
city varchar2(50),
state varchar2(25),
zip_code varchar2(10),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
Based on the departments table below, create an Oracle table called employees that stores employee number, employee name, department, and salary information. The primary key for the employees table should be the employee number. Create a foreign key on the employees table that references the departments table based on the department_id field.
CREATE TABLE departments
( department_id number(10) NOT NULL,
department_name varchar2(50) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id)
);
The Oracle CREATE TABLE statement for the employees table is:
CREATE TABLE employees
( employee_number number(10) NOT NULL,
employee_name varchar2(50) NOT NULL,
department_id number(10),
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY (employee_number),
CONSTRAINT fk_departments
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
);