smartyfy.mrindigi.com

Databases & SQL Master Course — 062. UNIQUE and Candidate Keys

Lesson 062 UNIQUE and Candidate Keys

Prerequisites and objectives

You understand required values and basic primary keys. You will now identify alternate candidate keys, enforce single-column and composite uniqueness, and explain SQLite’s handling of NULL in a UNIQUE constraint. The example catalogs fictional editions with both internal identifiers and business codes.

Create the practice fixture

Use a fresh disposable SQLite database. Each edition has a generated-style internal identifier, a required catalog code, an optional external code, and a series/edition-number pair. The two initial editions intentionally have NULL external codes. All exercises restore the fixture after testing accepted and rejected rows.

CREATE TABLE editions (
 edition_id INTEGER PRIMARY KEY,
 catalog_code TEXT NOT NULL UNIQUE,
 external_code TEXT UNIQUE,
 series_code TEXT NOT NULL,
 edition_no INTEGER NOT NULL,
 UNIQUE(series_code,edition_no)
);
INSERT INTO editions VALUES
 (1,'CAT-1',NULL,'MAP',1),
 (2,'CAT-2',NULL,'MAP',2);

Distinguish identity from a convenient label

A candidate key is a minimal set of attributes that uniquely identifies a row under the business rules. Minimal means that removing any attribute would lose the guaranteed uniqueness. A primary key is the candidate chosen as the table’s principal identifier; other candidates still deserve enforcement if the domain promises their uniqueness.

Here catalog_code is a required alternate identifier. The pair series_code and edition_no is another candidate under the stated rule that a series has at most one edition with a given number. Neither component alone is unique: a series can have several editions, and different series can each have edition one.

BEGIN;
INSERT INTO editions VALUES (3,'CAT-3','EXT-3','GUIDE',1);
SELECT series_code,edition_no FROM editions ORDER BY series_code,edition_no;
INSERT INTO editions VALUES (4,'CAT-4','EXT-4','MAP',1);
ROLLBACK;

GUIDE edition one is accepted because the entire pair differs from MAP edition one. A second MAP edition one is rejected even though it has a different internal identifier and catalog code. This is why adding a surrogate identifier does not eliminate the need for business uniqueness rules.

Edition rows 1/CAT-1/MAP-1/NULL, 2/CAT-2/MAP-2/NULL and 3/CAT-3/GUIDE-1/EXT-3 satisfy the key rules. Proposed row 4 has a new ID and catalog code but repeats pair MAP, 1, so it is rejected. Two NULL external codes coexist under SQLite UNIQUE semantics.
Each independently promised identity needs enforcement. A surrogate primary key does not replace the complete business-key constraint. Open full-size diagram

Read nullable uniqueness carefully

SQLite allows multiple NULL values in a UNIQUE column. That is useful for an optional external identifier: several editions may not yet have one, while a known external code must not be assigned twice. Such a nullable column is not a complete required candidate key for identifying every row.

Do not generalize the exact NULL policy to every database product or configuration. Also distinguish UNIQUE constraint behavior from SELECT DISTINCT, which collapses repeated NULL results in SQLite. The same word unique in casual conversation can conceal different SQL operations and different treatment of unknown values.

Specify the comparison rule

A uniqueness guarantee uses the column or index comparison semantics. Our codes use SQLite’s default BINARY collation, so CAT-1 and cat-1 are different text values. If the business treats them as the same code, choose and test an appropriate normalization and comparison policy rather than assuming the default enforces that meaning.

Do not use a person’s display name as a key simply because the current sample contains no duplicates. Names can repeat and change. The candidate-key claim comes from a durable domain rule, with tests showing that the schema enforces it. A sample is evidence about present rows, not proof about all allowed future rows.

Plan uniqueness tests

For each proposed candidate, test a valid new value, an exact duplicate, a missing value, and a value differing in one component. For text identifiers also test case and surrounding spaces under the chosen policy. When a duplicate is rejected, confirm which rule failed; several independent unique constraints may exist on one table.

Constraints remain important even if the application checks for duplicates first. A preliminary SELECT is useful feedback, but it is not a substitute for enforcing the rule at the write boundary. Concurrent operations and alternative import paths can otherwise create a state that the application assumed impossible.

Four worked exercises

Exercise 1

Attempt a new edition that reuses catalog code CAT-1 but has otherwise new values.

Worked solution
BEGIN;
INSERT INTO editions VALUES (3,'CAT-1','EXT-3','GUIDE',1);
SELECT COUNT(*) FROM editions;
ROLLBACK;

The alternate code constraint rejects the row. A new internal identifier does not make a duplicate catalog code acceptable. The final count confirms that the failing statement did not insert a partial edition.

Exercise 2

Add a third edition with no external code. Count missing external identifiers.

Worked solution
BEGIN;
INSERT INTO editions VALUES (3,'CAT-3',NULL,'GUIDE',1);
SELECT COUNT(*) FROM editions WHERE external_code IS NULL;
ROLLBACK;

All three missing external values are permitted by SQLite UNIQUE. If the domain later requires an external identifier for every edition, that is a separate required-value rule and a migration problem for existing NULL rows.

Exercise 3

Assign one external code twice and verify that known duplicates are rejected.

Worked solution
BEGIN;
UPDATE editions SET external_code='EXT-A' WHERE edition_id=1;
UPDATE editions SET external_code='EXT-A' WHERE edition_id=2;
SELECT edition_id,external_code FROM editions ORDER BY edition_id;
ROLLBACK;

The first assignment remains tentative, while the second fails. Uniqueness does not imply that the entire transaction rolled back. The explicit final rollback restores both external codes to their original missing state.

Exercise 4

Test a lowercase catalog code under the declared default comparison.

Worked solution
BEGIN;
INSERT INTO editions VALUES (3,'cat-1',NULL,'GUIDE',1);
SELECT catalog_code FROM editions ORDER BY edition_id;
ROLLBACK;

The lowercase code is accepted under BINARY comparison. This result documents the current schema’s actual guarantee. If the business requires case-insensitive codes, revise the design and its tests rather than describing this acceptance as a database bug.

Knowledge check

Question 1

Why is series plus edition number a candidate here?

  1. Each component must separately be unique
  2. It contains every column in the table
  3. The full pair is minimal and guaranteed unique
  4. The pair appears once in the current sample
Answer and explanation

C. A composite candidate identifies a row through the combination, not each component alone.

Question 2

What does the internal identifier fail to enforce?

  1. Its own primary-key uniqueness
  2. Uniqueness of the business catalog code
  3. An identity for each stored edition
  4. A way to target one internal row
Answer and explanation

B. Separate business identifiers need their own constraints.

Question 3

How does SQLite UNIQUE treat these NULL external codes?

  1. Several are allowed
  2. Only one is allowed
  3. Each is changed to an empty string
  4. They are automatically generated
Answer and explanation

A. SQLite treats NULL values as distinct for UNIQUE constraints.

Question 4

What proves a proposed candidate key is a domain rule?

  1. No duplicates in a small sample
  2. A convenient column heading
  3. An explicit uniqueness requirement with minimal attributes
  4. A short display value
Answer and explanation

C. Observed sample uniqueness cannot establish a rule for every allowed future state.

Question 5

Why was cat-1 accepted beside CAT-1?

  1. SQLite UNIQUE comparisons are always case-insensitive
  2. Text keys are compared only by their length
  3. Catalog codes are unique only within the same internal identifier
  4. The schema uses BINARY text comparison
Answer and explanation

D. Comparison semantics determine which values count as equal for this constraint.

Pitfalls and summary

Do not mistake a new row identifier for permission to duplicate a business identity. Document candidate keys, minimality, nullability, and comparison rules together. Test whole composite values and known duplicates. A good uniqueness design protects the domain’s real identity rules while leaving genuinely optional identifiers optional.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references