Lesson 6 of 8 · Structured Query Language (SQL)

Constraints and Indexes

The rules that keep bad data out: what NOT NULL means, primary, unique, and foreign keys, check constraints and defaults, and how indexes support them and speed up queries.

Beginner 10 sections 9 min read

Why constraints matter

A constraint is a rule the database enforces on every insert and update. If a change breaks the rule, the database rejects it, no matter which application, script, or person tried to make it.

Applications check data too, but there are always other ways in: a second application, a data import, a DBA fixing something by hand. Constraints are the last line of defense, and the only one that can't be skipped. Each kind stops a different kind of bad data:

TRYING TO INSERT RESULT customer 1, Abena customer 7, name: NULL customer 8, email: kofi@example.com order 108, for customer 99 order 109, amount: -5 order 110, customer 2, amount: 60 PRIMARY KEY: ID already used NOT NULL: name is required UNIQUE: email already used FOREIGN KEY: no customer 99 CHECK: amount must be > 0 All rules pass: saved

The examples use the sample tables, with one addition: customers now have an email address.

ALTER TABLE sales.customers ADD (email VARCHAR2(100));

NOT NULL: a value is required

NULL means a value is missing or unknown. It isn't zero, and it isn't a space: it's the absence of any value. By default, any column can be NULL.

NOT NULL means the column must always have a value. Every insert must provide one (or the column must have a default), and no update can remove it:

INSERT INTO sales.customers (customer_id, name) VALUES (7, NULL);
ORA-01400: cannot insert NULL into ("SALES"."CUSTOMERS"."NAME")

Use NOT NULL for anything the data can't make sense without: a customer's name, an order's amount, its date. Leave it off for things that are genuinely optional, such as a customer's city.

  • In Oracle, an empty string is NULL. Inserting '' into a NOT NULL column fails too.
  • Adding NOT NULL to an existing column only works if no rows are already NULL. Otherwise Oracle refuses with ORA-02296: cannot enable (…) - null values found, and you have to fill in the missing values first.
  • NOT NULL with a default is a common pair: status VARCHAR2(10) DEFAULT 'PENDING' NOT NULL means inserts can leave the status out, but it can never end up empty.

Primary key: one ID per row

A primary key uniquely identifies each row in a table. It combines two rules: every value must be unique, and it can never be NULL. A table can have only one primary key, and every table should have one.

customer_id NUMBER CONSTRAINT customers_pk PRIMARY KEY

INSERT INTO sales.customers (customer_id, name) VALUES (1, 'Abena');
ORA-00001: unique constraint (SALES.CUSTOMERS_PK) violated

A primary key can be made of more than one column, called a composite key. An order's line items, for example, are identified by the order number and the line number together:

CREATE TABLE sales.order_items (
  order_id   NUMBER,
  line_no    NUMBER,
  product    VARCHAR2(50) NOT NULL,
  quantity   NUMBER       NOT NULL,
  CONSTRAINT order_items_pk PRIMARY KEY (order_id, line_no)
);

Natural keys and surrogate keys

A natural key is a real-world value that happens to be unique, such as an email address or a national ID number. A surrogate key is a meaningless number created just to be the ID, such as customer_id, usually generated by a sequence or identity column.

Most designs use surrogate keys. Real-world values change (people change email addresses), and when a primary key changes, every row that points to it has to change too. A surrogate key never needs to.

Unique key: no duplicates

A unique key makes sure no two rows share the same value, without making that column the table's ID. It's how you enforce natural keys such as email addresses:

ALTER TABLE sales.customers
  ADD CONSTRAINT customers_email_uk UNIQUE (email);

UPDATE sales.customers SET email = 'kofi@example.com' WHERE customer_id = 1;
1 row updated.

UPDATE sales.customers SET email = 'kofi@example.com' WHERE customer_id = 3;
ORA-00001: unique constraint (SALES.CUSTOMERS_EMAIL_UK) violated
Primary keyUnique keyNOT NULL
Blocks duplicatesYesYesNo
Blocks NULLsYesNo: many rows can be NULLYes
How many per tableOneAs many as you needOne per column
PurposeThe row's ID, which other tables point toOther values that must be uniqueValues that must be present

A unique key allows NULLs because NULL means "unknown", and two unknowns aren't considered equal. Several customers can have no email; they just can't share one. Add NOT NULL as well if the value is required.

Foreign key: links between tables

A foreign key links a child table to a parent table. Every value in the foreign key column must match a primary key (or unique key) value in the parent. This is called referential integrity: an order can never point to a customer who doesn't exist.

customer_id NUMBER NOT NULL
  CONSTRAINT orders_customer_fk REFERENCES sales.customers (customer_id)

It protects the link from both sides:

-- child side: no orders for customers who don't exist
INSERT INTO sales.orders (order_id, customer_id, amount) VALUES (108, 99, 50);
ORA-02291: integrity constraint (SALES.ORDERS_CUSTOMER_FK) violated - parent key not found

-- parent side: no deleting customers who still have orders
DELETE FROM sales.customers WHERE customer_id = 1;
ORA-02292: integrity constraint (SALES.ORDERS_CUSTOMER_FK) violated - child record found

A foreign key column can be NULL unless you add NOT NULL, which is how you model an optional link. Here, every order must have a customer, so the column is NOT NULL as well.

What happens when a parent is deleted

By default, Oracle refuses to delete a parent that still has children. You can choose a different behavior when you create the foreign key:

(default)ON DELETE CASCADEON DELETE SET NULL customer 1: Kofi order 101 → 1 order 103 → 1 order 106 → 1 customer 1: Kofi order 101 → 1 order 103 → 1 order 106 → 1 customer 1: Kofi order 101 → NULL order 103 → NULL order 106 → NULL refused: ORA-02292 orders deleted too orders kept, link cleared
-- delete the children along with the parent
REFERENCES sales.customers (customer_id) ON DELETE CASCADE

-- keep the children, but clear the link (the column must allow NULL)
REFERENCES sales.customers (customer_id) ON DELETE SET NULL

Check constraints: custom rules

A check constraint is a condition every row must meet. It can test anything about the row's own values:

CONSTRAINT orders_amount_ck CHECK (amount > 0)
CONSTRAINT orders_status_ck CHECK (status IN ('PENDING', 'SHIPPED', 'CANCELLED'))

UPDATE sales.orders SET status = 'LOST' WHERE order_id = 101;
ORA-02290: check constraint (SALES.ORDERS_STATUS_CK) violated

A check can compare columns in the same row too, such as CHECK (ship_date >= order_date). It can't look at other rows or other tables; that's what unique and foreign keys are for.

Defaults

A default isn't a constraint, but it's defined alongside them. It's the value used when an insert leaves the column out:

order_date DATE         DEFAULT SYSDATE   NOT NULL
status     VARCHAR2(10) DEFAULT 'PENDING' NOT NULL

A default only fills in missing columns. An insert that explicitly sets a column to NULL still gets NULL, and NOT NULL then rejects it.

Indexes

An index isn't a constraint either, but the two are closely linked. An index is a separate, sorted copy of one or more columns, with a pointer to each row. Like the index at the back of a book, it lets the database jump straight to the rows it needs instead of reading the whole table.

Indexes that are created for you

To check a primary key or unique key quickly, Oracle needs a sorted list of the existing values, so it automatically creates a unique index with the same name as the constraint. Creating customers_pk also creates an index called CUSTOMERS_PK.

Foreign keys don't get an index automatically. Create one yourself on every foreign key column:

CREATE INDEX sales.orders_customer_idx ON sales.orders (customer_id);

Index created.

Without it, every lookup of a customer's orders reads the whole orders table. Worse, deleting or updating a customer forces Oracle to lock the entire orders table while it checks for children.

Indexes on several columns

A composite index covers more than one column, and the column order matters. Like a phone book sorted by surname and then first name, it helps when you search by the first column, but not by the second on its own:

INDEX ON (city, name) AccraKofi AccraYaw KumasiAma TamaleKwame (null)Esi sorted by city,then by name WHERE city = 'Accra' Uses the index: jumps to the Accra entries WHERE city = 'Accra' AND name = 'Yaw' Uses the index: jumps to a single entry WHERE name = 'Yaw' Usually can't: names aren't in order on their own
CREATE INDEX sales.customers_city_name_idx ON sales.customers (city, name);

Put the column you search by most often first.

When an index can't help

  • A function on the column. WHERE UPPER(name) = 'KOFI' can't use an ordinary index on name, because the index stores names as they are. A function-based index, CREATE INDEX … ON sales.customers (UPPER(name)), solves this.
  • A wildcard at the start. LIKE 'Ko%' can use an index; LIKE '%fi' can't, just as a phone book can't find everyone whose name ends in "fi".
  • Most of the table matches. If a query needs most of the rows anyway, reading the whole table is faster, and the optimizer will choose to.
  • Small tables. A table that fits in a few blocks is quicker to read in full.

Naming constraints

Always name constraints. A common convention is the table name plus a suffix for the type:

TypeSuffixExample
Primary key_pkorders_pk
Unique key_ukcustomers_email_uk
Foreign key_fkorders_customer_fk
Check_ckorders_amount_ck
Index_idxorders_customer_idx

Unnamed constraints get names such as SYS_C008120, which tell you nothing when they appear in an error message.

Key takeaways

  • Constraints are rules the database enforces on every change, no matter where it comes from.
  • NOT NULL means a value is required. NULL means "no value", and in Oracle an empty string counts as NULL.
  • A primary key is unique and never NULL: one per table, and usually a surrogate number.
  • A unique key blocks duplicates but allows NULLs; a table can have many.
  • A foreign key makes every child row point to a real parent row. Deleting a parent is refused by default, or can cascade or set the link to NULL.
  • Check constraints enforce custom rules, but let NULLs through, so pair them with NOT NULL.
  • Primary and unique keys get an index automatically; foreign keys don't, so index them yourself. Composite index column order matters.
  • Name every constraint, so error messages tell you which rule was broken.