Sub topic 1
Anatomy of a CREATE TABLE Statement
This chapter assumes you can run basic SQL (SELECT, INSERT, UPDATE, DELETE), understand tables, rows, and keys, and have access to an Oracle 12c or later schema through SQL*Plus, SQLcl, or SQL Developer.
Prerequisites
Read this chapter with a working Oracle schema open. Each example can run as written in a scratch schema.
Structure of a CREATE TABLE statement
A CREATE TABLE statement has three parts: the table name, a list of column definitions, and optional table-level constraints. Each column definition has a name, a data type, and optionally a default value and column constraints.
CREATE TABLE employees (
employee_id NUMBER(6),
email VARCHAR2(255),
hire_date DATE,
salary NUMBER(10,2)
);Choosing data types and column defaults
Choose types that match the data. VARCHAR2(n) stores variable-length text up to n characters. NUMBER(p,s) stores numbers with p total digits and s digits after the decimal point. DATE stores both date and time in Oracle.
A DEFAULT clause supplies a value when an INSERT omits the column. It must appear before any column constraints.
CREATE TABLE employees (
employee_id NUMBER(6),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL,
hire_date DATE DEFAULT SYSDATE
);Constraints: inline, out-of-line and named
A constraint is a rule the database enforces on the data. You can write a constraint inline, inside a column definition, or out-of-line, as a separate item after the column list. Both forms enforce the same rule. Out-of-line form is required when a constraint covers more than one column.
Give each constraint a name with CONSTRAINT name. Named constraints produce readable error messages and can be dropped or changed later by name.
CREATE TABLE employees (
employee_id NUMBER(6) CONSTRAINT employees_pk PRIMARY KEY,
email VARCHAR2(255),
salary NUMBER(10,2),
CONSTRAINT employees_salary_ck CHECK (salary >= 0)
);> Oracle does not accept an out-of-line NOT NULL. Write NOT NULL inline.
Requiring values with NOT NULL
NOT NULL rejects any row where the column has no value. It is always written inline. You can name it:
CREATE TABLE employees (
email VARCHAR2(255) CONSTRAINT employees_email_nn NOT NULL
);Oracle treats an empty string as NULL for VARCHAR2 columns, so NOT NULL also rejects empty text.
-- Fails with ORA-01400: cannot insert NULL
INSERT INTO employees (employee_id, email) VALUES (1, NULL);Exercise
Exercise
Write a CREATE TABLE statement for projects with these columns: projectid as a NUMBER(6) primary key, a projectname as VARCHAR2(100) that cannot be null, and createdon as a DATE that defaults to SYSDATE. Name the primary key projectspk.
Show answer
CREATE TABLE projects ( projectid NUMBER(6) CONSTRAINT projectspk PRIMARY KEY, projectname VARCHAR2(100) NOT NULL, createdon DATE DEFAULT SYSDATE );