Sub topic 2
Identifying rows with PRIMARY KEY
This chapter assumes you can write CREATE TABLE and INSERT statements, that you know the basic relational terms (table, row, column), and that you have an Oracle 12c or later schema. You can run every example in SQL*Plus, SQLcl, or SQL Developer.
Primary keys
A primary key identifies each row. Oracle enforces it with a unique index and an implicit NOT NULL rule, so every row needs a distinct, non-null key. A table can have only one primary key, which can span several columns.
CREATE TABLE departments (
department_id NUMBER,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id)
);
INSERT INTO departments (department_id, department_name) VALUES (10, 'Sales');
-- Fails with ORA-00001: unique constraint violated.
INSERT INTO departments (department_id, department_name) VALUES (10, 'Support');Preventing duplicates with UNIQUE
A UNIQUE constraint blocks duplicate values in a column that is not the primary key. Oracle allows several NULLs in a single-column UNIQUE column, but a primary key never accepts NULL.
Validating values with CHECK
A CHECK constraint tests each row against a Boolean condition. Oracle rejects any insert or update where the condition evaluates to FALSE. A NULL result passes, so pair CHECK with NOT NULL when a value is required.
Generating keys with identity columns
An identity column makes Oracle generate key values from an internal sequence. GENERATED ALWAYS rejects values you supply. GENERATED BY DEFAULT ON NULL accepts a supplied value and generates one only when the value is NULL.
CREATE TABLE employees (
employee_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY
(START WITH 1000 INCREMENT BY 1 CACHE 20),
email VARCHAR2(255) NOT NULL,
salary NUMBER(10,2),
CONSTRAINT employees_pk PRIMARY KEY (employee_id),
CONSTRAINT employees_email_uk UNIQUE (email),
CONSTRAINT employees_salary_ck CHECK (salary >= 0)
);Exercise
Exercise
The employees table uses GENERATED BY DEFAULT ON NULL. What happens when you insert employee_id = NULL?
Show answer
Oracle generates the next identity value, starting from 1000 in this table, and stores it in employee_id.