Sub topic 5
Identifying rows with PRIMARY KEY
A primary key is the column, or set of columns, that identifies each row in a table. This chapter covers what Oracle enforces for a primary key, the inline and out-of-line syntax, composite keys, the index Oracle builds behind the scenes, and the errors you will meet most often.
This chapter assumes you can write basic SELECT, INSERT, UPDATE and DELETE statements. It also assumes you know what a table, a row and a key are, and that you have an Oracle Database 12c or later schema to run the examples in.
What a primary key guarantees
A PRIMARY KEY constraint combines two rules:
- Uniqueness. No two rows may have the same key value.
- Presence. No key column may be
NULL. Oracle adds the not-null rule for you, so you do not writeNOT NULLon a primary key column.
A table can have at most one primary key. It can have many UNIQUE constraints, which the next chapter covers. A primary key is the row's identity, and other tables point to it with foreign keys.
| Property | PRIMARY KEY | UNIQUE |
|---|---|---|
| Per table | At most one | Any number |
| NULLs allowed | Never | Yes, with some rules |
| Can be referenced by a foreign key | Yes | Yes |
| Typical role | Row identity | Alternate natural key |
Declaring a primary key
You can declare the constraint in two places. Both forms create the same kind of constraint.
Inline (column level)
An inline constraint sits on the column definition. It works only for single-column keys.
CREATE TABLE regions (
region_id NUMBER CONSTRAINT regions_pk PRIMARY KEY,
region_name VARCHAR2(50) NOT NULL
);Out of line (table level)
An out-of-line constraint is listed after all the columns. This is the only form that supports composite keys, and it keeps constraint definitions together. The examples in this tutorial use it.
CREATE TABLE departments (
department_id NUMBER GENERATED ALWAYS AS IDENTITY,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id),
CONSTRAINT departments_name_uk UNIQUE (department_name)
);Here departments_pk is the constraint name. The identity clause on department_id generates the key values, which a later chapter covers in detail.
Always name the constraint
If you write PRIMARY KEY without CONSTRAINT name, Oracle invents a name such as SYS_C0012345. System names differ between databases, so scripts that refer to them break when moved from development to production. Error messages are also harder to read. Compare these two:
ORA-00001: unique constraint (HR.DEPARTMENTS_PK) violatedORA-00001: unique constraint (HR.SYS_C0012345) violated
The first tells you the table and the rule at once. A common convention is <table>_pk.
Composite primary keys
A composite key uses more than one column. The combination must be unique, and every column in it must be non-null. Individual columns may repeat.
CREATE TABLE order_items (
order_id NUMBER NOT NULL,
line_no NUMBER(4) NOT NULL,
product_id NUMBER NOT NULL,
quantity NUMBER(6) DEFAULT 1 NOT NULL,
CONSTRAINT order_items_pk PRIMARY KEY (order_id, line_no)
);
INSERT INTO order_items (order_id, line_no, product_id) VALUES (1, 1, 100);
INSERT INTO order_items (order_id, line_no, product_id) VALUES (1, 2, 101);
INSERT INTO order_items (order_id, line_no, product_id) VALUES (2, 1, 100);
-- Fails with ORA-00001: the pair (1, 1) already exists.
INSERT INTO order_items (order_id, line_no, product_id) VALUES (1, 1, 102);The first three rows succeed because no pair repeats, even though order_id and line_no values each appear more than once. The fourth fails.
The order of columns in a composite key matters. Oracle builds an index on the columns in the order you list them. A query that filters on order_id alone can use that index. A query that filters on line_no alone usually cannot use it efficiently.
The index behind the constraint
To enforce uniqueness quickly, Oracle needs an index on the key columns. When you create a primary key, Oracle does one of two things:
- If no usable index exists, it creates a unique index named after the constraint (here
DEPARTMENTS_PK). - If an index on the same leading columns already exists, it can use that index.
You can control this with a USING INDEX clause.
CREATE TABLE products (
product_id NUMBER NOT NULL,
product_name VARCHAR2(100) NOT NULL,
CONSTRAINT products_pk PRIMARY KEY (product_id)
USING INDEX (CREATE UNIQUE INDEX products_pk_ix ON products (product_id))
);Most of the time the default is fine. The clause matters when you want the index in a specific tablespace or with a different name.
Dropping a primary key normally drops its index too, if Oracle created the index for it. If you created the index yourself, the index stays unless you add DROP INDEX to the ALTER TABLE statement. Dropping a key that other tables reference fails unless you add CASCADE, which also drops the dependent foreign keys.
Choosing a good key
Good primary keys share these traits:
- Stable. The value never changes after the row exists. Changing a key means updating every row that references it.
- Unique and always known. Every row has a value from the moment it is inserted.
- Compact. Small keys make smaller indexes, and every foreign key repeats the key's size.
There are two common approaches.
| Approach | Example | Advantages | Drawbacks |
|---|---|---|---|
| Surrogate key | Identity column `employee_id` | Stable, compact, meaningless so never needs to change | Carries no business meaning, so you usually add a `UNIQUE` constraint on the natural identifier |
| Natural key | Country code, email address | Meaningful, readable in queries | Values can change, can be long, can turn out not to be unique |
For most tables, use a surrogate identity key as the primary key and put a UNIQUE constraint on the natural identifier, as the employees_email_uk constraint does in this tutorial's employees table.
What happens on violation
Oracle checks the key on every INSERT and on every UPDATE that changes key columns. Two errors cover most cases:
| Error | Cause |
|---|---|
| `ORA-00001: unique constraint (...) violated` | A row with the same key value already exists. |
| `ORA-01400: cannot insert NULL into (...)` | A key column was left `NULL`, or was omitted with no default. |
The statement fails as a whole. Oracle rolls back that single statement and leaves earlier work in your transaction untouched. In a multi-row INSERT ... SELECT, one duplicate causes the entire statement to roll back.
Gotchas
- Data types and trailing details. Two
VARCHAR2values that differ only in case, such as'abc'and'ABC', are different keys. Oracle compares them exactly by default. - Empty strings. Oracle treats an empty string as
NULL. AVARCHAR2key therefore cannot be an empty string. - Inserting explicit values into identity keys. With
GENERATED ALWAYS, supplying a value fails. WithBY DEFAULT, you can supply a value that later collides with a generated one, producingORA-00001. The next chapters on identity modes cover this. - Updating keys. Oracle allows you to update a primary key value, but only if no foreign key rows reference it. Oracle has no
ON UPDATE CASCADE, which is another reason to keep keys stable. - Wide composite keys. Every table that references a composite key must carry all of its columns. If that gets awkward, use a single surrogate key instead and a
UNIQUEconstraint over the composite columns.
Checking the result
You can confirm the primary key from the data dictionary. constraint_type is P for primary keys.
SELECT c.constraint_name, cc.column_name, cc.position
FROM user_constraints c
JOIN user_cons_columns cc
ON cc.constraint_name = c.constraint_name
WHERE c.table_name = 'ORDER_ITEMS'
AND c.constraint_type = 'P'
ORDER BY cc.position;For order_items this returns ORDER_ITEMS_PK twice, once for ORDER_ID at position 1 and once for LINE_NO at position 2.
Exercise
A table enrollments links students to courses. A student may enroll in many courses, a course has many students, and one student can enroll in a given course only once. Write the CREATE TABLE statement with a named, out-of-line primary key, using columns student_id and course_id. What error does a duplicate enrollment raise?
Show answer
CREATE TABLE enrollments ( studentid NUMBER NOT NULL, courseid NUMBER NOT NULL, enrolledon DATE DEFAULT SYSDATE NOT NULL, CONSTRAINT enrollmentspk PRIMARY KEY (studentid, courseid) ); A composite key makes the pair unique while allowing each student and each course to appear many times. Inserting the same pair twice raises ORA-00001: unique constraint (SCHEMA.ENROLLMENTS_PK) violated. The explicit NOT NULL clauses are optional because a primary key already forbids NULLs.
Exercise
You run INSERT INTO departments (department_id, department_name) VALUES (1, 'HR'); against the departments table in this chapter, and it fails even though no row has ID 1. Why, and how do you fix it?
Show answer
The column is GENERATED ALWAYS AS IDENTITY, so Oracle rejects any explicit value with ORA-32795. Omit the column and let Oracle generate it: INSERT INTO departments (department_name) VALUES ('HR');