apps-dba journal

A working journal for Oracle DBAs.

March 27, 2026

Oracle SQL DDL: CREATE TABLE, Data Types and Constraints

Oracle SQL DDL: CREATE TABLE and Constraints – Complete Guide

Oracle SQL DDL: CREATE TABLE and Constraints – Complete Guide

The CREATE TABLE statement is the foundation of every Oracle database. It defines the structure of your tables, the data types for each column, and the rules (constraints) that protect the integrity of your data.

Learning Objectives
By the end of this guide you will know how to create tables, choose the right data types, define all five constraint types, understand column-level vs table-level syntax, and use CREATE TABLE AS SELECT effectively.

1. CREATE TABLE – Basic Syntax

CREATE TABLE departments (
    department_id   NUMBER(4)    CONSTRAINT dept_id_pk PRIMARY KEY,
    department_name VARCHAR2(30) CONSTRAINT dept_name_nn NOT NULL,
    manager_id      NUMBER(6),
    location_id     NUMBER(4)
);

2. Common Oracle Data Types

Data TypeWhat it storesKey points
VARCHAR2(n)Variable-length character stringMaximum length n is required
CHAR(n)Fixed-length character stringShorter values are padded with spaces
NUMBER(p,s)Numbers with precision and scaleBoth p and s are optional
DATEDate and time (including time of day)Always stores hours, minutes, seconds
TIMESTAMPDate with fractional secondsHigher precision than DATE

3. The Five Constraint Types

ConstraintEnforcesAllows NULL?
NOT NULLColumn must contain a valueNo
PRIMARY KEYUnique + NOT NULL identifierNo
UNIQUENo duplicate valuesYes (multiple NULLs allowed)
FOREIGN KEYValue must exist in referenced tableYes
CHECKValue must satisfy a conditionYes (NULL passes CHECK)

4. Column-Level vs Table-Level Constraints

Most constraints can be defined either inline with the column or at the table level after all columns are listed. NOT NULL must be column-level only.
-- Column-level (inline)
employee_id NUMBER(6) CONSTRAINT emp_id_pk PRIMARY KEY,

-- Table-level (after columns)
CONSTRAINT emp_id_pk PRIMARY KEY (employee_id)

5. NOT NULL Constraint

```sql last_name VARCHAR2(25) NOT NULL

No comments:

Post a Comment

Oracle DBA Lesson 17B — Run a Repeatable SQL*Plus Report

A report you will run again is a script: fixed line and page size, column formats, a spool file, and an exit that means what it says. A...