Lesson 5 of 8 · Structured Query Language (SQL)

Defining Structure with DDL

How to create and change tables with DDL: data types, constraints that keep bad data out, ALTER, the difference between DELETE, TRUNCATE, and DROP, and other objects.

Beginner 9 sections 7 min read

What DDL does

DDL (Data Definition Language) creates and changes the structure that holds the data: tables, their columns and rules, and objects such as indexes, views, and sequences.

The main DDL commands are CREATE, ALTER, DROP, TRUNCATE, and RENAME. DDL is where most of a DBA's design decisions live: a well-designed table keeps bad data out on its own.

Creating a table

Here's how the two sample tables are created. Each column has a name, a data type, and optional rules:

CREATE TABLE sales.customers (
  customer_id NUMBER        CONSTRAINT customers_pk PRIMARY KEY,
  name        VARCHAR2(50)  NOT NULL,
  city        VARCHAR2(50),
  joined_on   DATE          DEFAULT SYSDATE NOT NULL
);

Table created.

CREATE TABLE sales.orders (
  order_id    NUMBER        CONSTRAINT orders_pk PRIMARY KEY,
  customer_id NUMBER        NOT NULL
              CONSTRAINT orders_customer_fk REFERENCES sales.customers (customer_id),
  order_date  DATE          DEFAULT SYSDATE NOT NULL,
  amount      NUMBER(10,2)  NOT NULL
              CONSTRAINT orders_amount_ck CHECK (amount > 0),
  status      VARCHAR2(10)  DEFAULT 'PENDING' NOT NULL
              CONSTRAINT orders_status_ck CHECK (status IN ('PENDING', 'SHIPPED', 'CANCELLED'))
);

Table created.

The parent table, customers, has to exist first, because orders points to it.

Naming rules

  • Names start with a letter and can contain letters, numbers, and _, up to 128 characters.
  • Oracle stores names in uppercase: customers becomes CUSTOMERS.
  • Avoid names in double quotes, such as "Order Date". They keep spaces and lowercase letters, but then every query must quote them exactly the same way.

Data types

A column's data type decides what it can hold. These are the Oracle types you'll use most:

TypeHoldsExample
NUMBER(p,s)Numbers. p is the total number of digits, s the digits after the decimal point. Plain NUMBER takes any number.NUMBER(10,2) holds up to 99999999.99
VARCHAR2(n)Text of varying length, up to n bytes (normally at most 4,000)VARCHAR2(50)
CHAR(n)Text of a fixed length, padded with spacesCHAR(2) for a country code
DATEA date and a time, to the secondDATE '2026-01-10'
TIMESTAMPA date and time with fractions of a secondEvent logs
CLOB, BLOBLarge text, and large binary data such as filesDocuments, images

Constraints: rules the database enforces

Constraints are rules attached to a table. The database checks them on every insert and update, and rejects any change that breaks one, no matter which application or person makes it. Here's a quick overview; the next lesson, Constraints and Indexes, covers each one in depth.

sales.orders order_idcustomer_idorder_dateamountstatus NUMBERNUMBERDATENUMBER(10,2)VARCHAR2(10) PRIMARY KEY NOT NULL FOREIGN KEY → customers DEFAULT SYSDATE NOT NULL NOT NULL CHECK amount > 0 DEFAULT 'PENDING' NOT NULL CHECK status IN (…)
RuleWhat it doesError when broken
PRIMARY KEYUniquely identifies each row. It can't be empty or repeated, and every table should have one.ORA-00001
FOREIGN KEY (REFERENCES)The value must exist in another table's key, so an order can't point to a missing customer.ORA-02291, ORA-02292
UNIQUENo two rows can have the same value, such as an email address. Unlike a primary key, it allows NULL.ORA-00001
NOT NULLThe column must have a value.ORA-01400
CHECKThe value must pass a test, such as amount > 0.ORA-02290
DEFAULTNot a constraint, but related: the value used when an insert leaves the column out.

Looking at a table's structure

In SQL*Plus, DESCRIBE (or DESC) lists a table's columns:

SQL> DESC sales.orders
 Name                 Null?    Type
 -------------------- -------- -------------
 ORDER_ID             NOT NULL NUMBER
 CUSTOMER_ID          NOT NULL NUMBER
 ORDER_DATE           NOT NULL DATE
 AMOUNT               NOT NULL NUMBER(10,2)
 STATUS               NOT NULL VARCHAR2(10)

For the full picture, including constraints, query the data dictionary:

SELECT constraint_name, constraint_type
FROM   dba_constraints
WHERE  owner = 'SALES' AND table_name = 'ORDERS';

Changing a table with ALTER

ALTER TABLE changes an existing table without losing its data:

-- add a column
ALTER TABLE sales.customers ADD (email VARCHAR2(100));

-- make a column longer
ALTER TABLE sales.customers MODIFY (city VARCHAR2(100));

-- rename a column
ALTER TABLE sales.customers RENAME COLUMN email TO email_address;

-- add a rule to an existing table
ALTER TABLE sales.customers ADD CONSTRAINT customers_email_uk UNIQUE (email_address);

-- remove a column and its data
ALTER TABLE sales.customers DROP COLUMN email_address;

Table altered.

Some changes need care on a table that already has data. Adding a NOT NULL column fails unless you give it a default, and making a column shorter fails if existing values don't fit.

Removing data and tables

Three statements remove things, and they're easy to mix up:

DELETETRUNCATEDROP removes chosen rowscan be rolled back removes all rows, fastcan't be rolled back removes the table itselfto the recycle bin DML DDL DDL
DELETETRUNCATE TABLEDROP TABLE
RemovesThe rows matching WHERE, or all rowsAll rowsThe table, its data, indexes, and constraints
The table afterwardsStill thereStill there, emptyGone
Undo with ROLLBACK?Yes, until you commitNoNo, but see the recycle bin below
Speed on a big tableSlow: every row is loggedFastFast
Frees the space?No, the space is reused for new rowsYesYes, once purged
TRUNCATE TABLE sales.orders_archive;

Table truncated.

DROP TABLE sales.orders_archive;

Table dropped.

A dropped table goes to the recycle bin, so it can be brought back with FLASHBACK TABLE sales.orders_archive TO BEFORE DROP;. DROP TABLE … PURGE skips the recycle bin and removes the table for good.

Foreign keys protect parent tables too. You can't drop customers while orders still points to it:

DROP TABLE sales.customers;
ORA-02449: unique/primary keys in table referenced by foreign keys

Creating other objects

The same CREATE pattern makes every other kind of object:

-- a copy of a table's columns, with no rows, using CREATE TABLE ... AS SELECT
CREATE TABLE sales.orders_archive AS
  SELECT * FROM sales.orders WHERE 1 = 0;

-- an index to speed up lookups by customer
CREATE INDEX sales.orders_customer_idx ON sales.orders (customer_id);

-- a view: a saved query that acts like a table
CREATE VIEW sales.order_details AS
  SELECT c.name, o.order_id, o.amount, o.status
  FROM   sales.customers c
  JOIN   sales.orders o ON o.customer_id = c.customer_id;

-- a sequence that hands out order numbers, starting at 108
CREATE SEQUENCE sales.orders_seq START WITH 108;

Once a view exists, you query it like a table: SELECT * FROM sales.order_details WHERE name = 'Kofi';. A sequence gives the next number with NEXTVAL:

INSERT INTO sales.orders (order_id, customer_id, amount)
VALUES (sales.orders_seq.NEXTVAL, 2, 60);

Since Oracle 12c, an identity column can do this for you: order_id NUMBER GENERATED ALWAYS AS IDENTITY numbers new rows automatically.

Key takeaways

  • DDL defines structure: CREATE, ALTER, DROP, TRUNCATE, and RENAME. In Oracle, it commits automatically.
  • Every column has a data type. Oracle's DATE includes a time.
  • Constraints (primary key, foreign key, unique, not null, and check) make the database itself reject bad data. Name them.
  • ALTER TABLE changes a table without losing its data.
  • DELETE removes rows and can be rolled back; TRUNCATE empties a table instantly and can't; DROP removes the table to the recycle bin.
  • Indexes, views, and sequences are created the same way, with CREATE.