Sub topic 3
How constraints work: inline, out-of-line and named
This chapter assumes you can write basic SELECT, INSERT, UPDATE and DELETE statements. It also assumes you have seen a simple CREATE TABLE and know what a primary key is. You need an Oracle Database 12c or later schema where you can create tables.
What a constraint is
A constraint is a rule that the database enforces on the data in a table. Every INSERT, UPDATE, MERGE and DELETE that would break the rule fails with an error, and the statement is rolled back. The rule lives in the table definition, so it applies to every application and every person who touches the table.
Oracle supports five constraint types:
| Type | Code in `USER_CONSTRAINTS` | Rule |
|---|---|---|
| NOT NULL | `C` | The column must have a value. |
| PRIMARY KEY | `P` | Each row is identified by a unique, non-null value or combination of values. |
| UNIQUE | `U` | No two rows share the same non-null value or combination of values. |
| CHECK | `C` | A condition must not evaluate to false. |
| FOREIGN KEY | `R` | The value must exist in the referenced parent key, or be null. |
NOT NULL and CHECK share the code C because Oracle stores a NOT NULL rule as a special kind of check condition. Later chapters cover each type in detail. This chapter covers the syntax rules they all share: where you write a constraint, how you name it, and how Oracle treats it.
Two places to write a constraint
You can declare a constraint in one of two positions inside CREATE TABLE.
- Inline (also called column-level): the constraint is part of a column definition.
- Out-of-line (also called table-level): the constraint is a separate item in the list, after the column definitions.
Here is the same table written both ways.
-- Inline: constraints sit inside the column definitions.
CREATE TABLE products_inline (
product_id NUMBER CONSTRAINT products_inline_pk PRIMARY KEY,
sku VARCHAR2(30) CONSTRAINT products_inline_sku_nn NOT NULL
CONSTRAINT products_inline_sku_uk UNIQUE,
list_price NUMBER(10,2) CONSTRAINT products_inline_price_ck CHECK (list_price >= 0)
);
-- Out-of-line: constraints are listed after the columns.
CREATE TABLE products_outline (
product_id NUMBER,
sku VARCHAR2(30) NOT NULL,
list_price NUMBER(10,2),
CONSTRAINT products_outline_pk PRIMARY KEY (product_id),
CONSTRAINT products_outline_sku_uk UNIQUE (sku),
CONSTRAINT products_outline_price_ck CHECK (list_price >= 0)
);Notice that the inline sku column carries two constraints in a row, with no comma between them. The out-of-line version needs a column list in parentheses for PRIMARY KEY and UNIQUE, because the constraint is not attached to any one column.
Which form can express what
The two forms are not equal in power. This table shows the limits.
| Need | Inline | Out-of-line |
|---|---|---|
| NOT NULL | Yes | Only as a CHECK such as `CHECK (sku IS NOT NULL)` |
| Single-column PRIMARY KEY, UNIQUE | Yes | Yes |
| Composite (multi-column) PRIMARY KEY or UNIQUE | No | Yes |
| CHECK that reads one column | Yes | Yes |
| CHECK that compares two or more columns | No | Yes |
| FOREIGN KEY | Yes, using `REFERENCES` only | Yes, using `FOREIGN KEY (...) REFERENCES` |
Two of these rows are worth a closer look.
First, a composite key must be out-of-line. An order line, for example, is identified by the order and the line number together:
CREATE TABLE order_lines (
order_id NUMBER NOT NULL,
line_number NUMBER(4) NOT NULL,
quantity NUMBER(6) NOT NULL,
CONSTRAINT order_lines_pk PRIMARY KEY (order_id, line_number),
CONSTRAINT order_lines_qty_ck CHECK (quantity > 0)
);Second, a CHECK that compares two columns must be out-of-line, because an inline CHECK may refer only to its own column:
CREATE TABLE contracts (
contract_id NUMBER,
start_date DATE NOT NULL,
end_date DATE,
CONSTRAINT contracts_pk PRIMARY KEY (contract_id),
CONSTRAINT contracts_dates_ck CHECK (end_date IS NULL OR end_date >= start_date)
);The NOT NULL on start_date is written inline, which is the usual practice. Oracle has no separate out-of-line NOT NULL syntax, so a plain NOT NULL is always attached to a column definition.
Naming constraints
Every constraint has a name. If you do not supply one, Oracle generates one such as SYS_C0012345. You supply a name by writing CONSTRAINT name immediately before the constraint definition, as the examples above do.
Generated names cause real problems:
- An error message reports the name, for example
ORA-02290: check constraint (HR.SYS_C0012345) violated. Nobody can tell from that name which rule failed. - The generated names differ between databases, so a script that says
DROP CONSTRAINT SYS_C0012345works in development and fails in production. - Tools that compare schemas see every generated name as a difference.
Compare the message you get with a name you chose:
INSERT INTO order_lines (order_id, line_number, quantity) VALUES (1, 1, 0);
-- ORA-02290: check constraint (YOUR_SCHEMA.ORDER_LINES_QTY_CK) violatedThe name now tells you the table and the rule.
A naming convention
Oracle does not require any pattern, but a consistent one pays off. A common choice is <table>_<column or purpose>_<suffix>:
| Suffix | Constraint type |
|---|---|
| `_pk` | PRIMARY KEY |
| `_uk` | UNIQUE |
| `_ck` | CHECK |
| `_fk` | FOREIGN KEY |
| `_nn` | NOT NULL |
Naming rules and limits
- Constraint names are identifiers. Unquoted names are stored in upper case and are case-insensitive.
- In Oracle Database 12.2 and later, an identifier can be up to 128 bytes. In 12.1 and earlier the limit is 30 bytes, so long table names leave little room for a suffix.
- Constraint names must be unique within a schema, not just within a table. Two tables in the same schema cannot both have a constraint called
status_ck. This is why the table name belongs in the constraint name. - A unique or primary key constraint creates an index. By default the index takes the constraint's name, which is another reason to choose a clear name.
Be careful with NOT NULL. If you write NOT NULL without a name, it gets a generated SYS_C name, which is the most common source of unnamed constraints. Name it inline when the name matters:
CREATE TABLE customers (
customer_id NUMBER CONSTRAINT customers_pk PRIMARY KEY,
last_name VARCHAR2(100) CONSTRAINT customers_last_name_nn NOT NULL
);How Oracle enforces a constraint
Oracle checks constraints at the end of each statement, not row by row as the statement runs. This matters for a statement that touches many rows. The following swap succeeds, even though the intermediate state would hold a duplicate:
CREATE TABLE seats (
seat_no NUMBER CONSTRAINT seats_no_uk UNIQUE
);
INSERT INTO seats VALUES (1);
INSERT INTO seats VALUES (2);
-- Swap the two values in one statement.
UPDATE seats SET seat_no = 3 - seat_no;A constraint can also be made deferrable so that the check moves to the COMMIT. That belongs to a later chapter on constraint states.
If any row in a statement breaks a constraint, the whole statement fails and none of its rows are changed. Earlier statements in the same transaction stay in place until you commit or roll back.
Nulls and constraints
Nulls behave differently for each type, and this surprises many people.
- PRIMARY KEY columns can never be null. Declaring a primary key makes all its columns NOT NULL implicitly.
- UNIQUE allows nulls. For a single-column unique constraint, any number of rows can hold null, because null is not equal to anything.
- For a composite UNIQUE constraint, a row is exempt from the check if every column is null. Rows with some columns null are compared on the remaining non-null columns together with the nulls, and two such rows with identical values conflict.
- CHECK passes when the condition is true or unknown.
CHECK (salary >= 0)accepts a null salary, becauseNULL >= 0is unknown. Add NOT NULL if a value is required. - FOREIGN KEY accepts a null in the child column, which means "no parent".
You can see the single-column UNIQUE behavior here:
CREATE TABLE badges (
badge_code VARCHAR2(10) CONSTRAINT badges_code_uk UNIQUE
);
INSERT INTO badges VALUES (NULL);
INSERT INTO badges VALUES (NULL); -- succeeds
INSERT INTO badges VALUES ('A1');
INSERT INTO badges VALUES ('A1'); -- fails: ORA-00001 unique constraint violatedCommon errors
| Error | Meaning | Typical cause |
|---|---|---|
| ORA-00001 | Unique constraint violated | Duplicate in a primary key or unique column |
| ORA-01400 | Cannot insert NULL | A NOT NULL column received no value |
| ORA-02290 | Check constraint violated | A value failed the CHECK condition |
| ORA-02291 | Integrity constraint violated, parent key not found | A foreign key value has no parent row |
| ORA-02292 | Integrity constraint violated, child record found | Deleting a parent row that children still reference |
| ORA-02264 | Name already used by an existing constraint | Two constraints share a name in the same schema |
| ORA-02260 | Table can have only one primary key | A second PRIMARY KEY in one table |
Looking at what you created
A quick query shows the names, types and conditions:
SELECT constraint_name, constraint_type, search_condition_vc
FROM user_constraints
WHERE table_name = 'CONTRACTS'
ORDER BY constraint_name;The search_condition_vc column is available in Oracle 12.2 and later. In earlier releases, search_condition holds the same text but is a LONG column, which is awkward to filter or compare. A later chapter covers the data dictionary views in full.
Choosing between inline and out-of-line
Both forms produce identical constraints. Choose by readability and by what the rule needs.
- Use inline for NOT NULL, and for a simple rule that belongs to one column.
- Use out-of-line for composite keys, for rules involving several columns, and for any constraint you want to keep together in one block.
- Always name the constraint, whichever form you use.
Many teams put every constraint except NOT NULL out-of-line. The column list then reads as a plain description of the data, and the rules form one block that is easy to review.
Exercise
A table bookings has columns room_id, booking_date, check_in and check_out. Write the out-of-line named constraints so that a room can be booked only once per date, and so that check_out is later than check_in. Then explain why the first rule cannot be written inline.
Show answer
CONSTRAINT bookingsroomdateuk UNIQUE (roomid, bookingdate), CONSTRAINT bookingstimesck CHECK (checkout > check_in). The first rule covers two columns together (a composite UNIQUE), and an inline constraint is attached to a single column definition, so a multi-column key must be written out-of-line. The second rule compares two columns, which an inline CHECK cannot do either.
Exercise
You run INSERT INTO badges VALUES (NULL) twice against a table whose only column has a single-column UNIQUE constraint. Does the second insert fail? What changes if the column is also declared as the PRIMARY KEY?
Show answer
The second insert succeeds, because a null is never equal to another null, so UNIQUE allows any number of null rows. With a PRIMARY KEY, the very first insert fails with ORA-01400, because a primary key column cannot be null.