smartyfy.mrindigi.com

Databases & SQL Master Course — 114. MySQL InnoDB Constraints

Lesson 114 MySQL InnoDB Constraints

Verification scope and lab safety

MySQL 8.4 only. These scripts were checked against official documentation but were not executed on that engine in the authoring environment. Every result below is a reasoned expectation, not observed output. Use a dedicated disposable local lab with the required privileges, never an existing application database. No server installation, credential changes, or external database operation is part of this lesson.

Prerequisites and objectives

Complete the MySQL mode lesson and understand parent-child keys. You will verify that an InnoDB fixture declares and enforces requiredness, uniqueness, checks, and foreign keys, and plan cleanup around MySQL’s nonrollbackable table definitions.

Use ordinary tables only in a dedicated disposable lab

MySQL foreign keys cannot be defined on temporary tables. This lesson therefore needs ordinary tables in an already provisioned disposable local database. Never adapt it to an existing application database. Confirm that both lesson table names are unused, that the account may create and remove its own lab objects, and that no other session uses this database.

Ordinary table creation causes implicit commits. Start with a fresh connection containing no pending application work. The DDL setup is separate from the transaction holding the practice rows. ROLLBACK will remove those rows, but it will not remove the table definitions. Cleanup explicitly drops only the two objects successfully created by this lab, child first.

SELECT DATABASE(), VERSION(), @@SESSION.foreign_key_checks;
SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE()
 AND table_name IN ('lab_depts114','lab_assets114');

If either name already exists, stop rather than deleting it or adding IF NOT EXISTS. If foreign_key_checks is not one, stop and resolve the lab configuration with its owner; disabling checks is not part of this exercise. The purpose is to test declared integrity under normal enforcement, not to bypass it.

Create compatible parent and child keys

The parent and child use InnoDB, and both department columns use the same unsigned integer type. The parent key is explicitly unique through its primary key. MySQL has additional compatibility and indexing requirements for foreign keys, including matching size and sign for these integer columns. A plain nonunique lookup index is not the model for this parent identity.

SET @saved_mode114 = @@SESSION.sql_mode;
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION';
CREATE TABLE lab_depts114 (
 dept_id INT UNSIGNED PRIMARY KEY, name VARCHAR(30) NOT NULL
) ENGINE=InnoDB;
CREATE TABLE lab_assets114 (
 asset_id INT UNSIGNED PRIMARY KEY,
 tag VARCHAR(20) NOT NULL,
 qty INT NOT NULL,
 dept_id INT UNSIGNED NOT NULL,
 CONSTRAINT lab_tag114 UNIQUE (tag),
 CONSTRAINT lab_qty114 CHECK (qty >= 0),
 CONSTRAINT lab_fk114 FOREIGN KEY (dept_id)
 REFERENCES lab_depts114(dept_id)
 ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB;
SHOW CREATE TABLE lab_assets114;
START TRANSACTION;
INSERT INTO lab_depts114 VALUES (1,'Studio');
INSERT INTO lab_assets114 VALUES (101,'A',2,1),(102,'B',0,1);

Separate each rule and its failure

The tag is required and unique. Quantity is required and nonnegative. Department identity is required and must reference the parent. These are separate obligations. A CHECK accepts a true or unknown condition, so NOT NULL separately excludes a missing quantity. Zero is allowed by the stated range rule.

MySQL 8.4 supports enforced CHECK constraints. Older MySQL releases had materially different behavior, so do not accept a parser’s recognition of CHECK as proof of enforcement on an unspecified server. Inspect the created definition and execute a negative test on the intended engine. This lesson’s expectations remain unobserved until that local run occurs.

Reasoned isolated integrity failures; not observed
Trial value Independent rule Expected result
NULL tag Requiredness Reject
Repeated A tag Uniqueness Reject
Quantity -1 Nonnegative CHECK Reject
Department 99 Foreign key Reject

Each trial below uses an unused asset identity and otherwise valid fields. That makes its expected failure specific. A savepoint gives the trial an explicit cleanup boundary. These ordinary integrity failures are expected to roll back the failing statement in InnoDB; do not generalize that behavior to every error. For example, a deadlock can roll back the whole transaction and invalidate earlier savepoint assumptions.

Worked practice

Exercise 1

Attempt a missing tag without also violating the quantity or department rule.

Worked solution
SAVEPOINT trial;
INSERT INTO lab_assets114 VALUES (103,NULL,1,1);
-- Expected error: inspect it before running the recovery lines.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;

The required tag is the intended failure. Quantity one is valid and department one exists. After inspecting the error, run the recovery lines in the same connection. If an unexpected error reports that the transaction or savepoint is gone, stop and inspect instead of blindly continuing the remaining trials.

Exercise 2

Attempt a repeated tag with a different asset identity.

Worked solution
SAVEPOINT trial;
INSERT INTO lab_assets114 VALUES (103,'A',1,1);
-- Expected error: inspect it before running the recovery lines.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;

The existing asset already uses tag A. A new primary-key identity does not satisfy the independent tag uniqueness requirement. These uppercase literal tags avoid a collation comparison dispute in the fixture; a case-sensitive tag policy would require an explicit collation choice and additional tests.

Exercise 3

Attempt a negative quantity.

Worked solution
SAVEPOINT trial;
INSERT INTO lab_assets114 VALUES (103,'C',-1,1);
-- Expected error: inspect it before running the recovery lines.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;

Minus one fits the signed integer type but violates the domain rule. The negative test therefore checks business integrity rather than a numeric storage overflow. Removing the CHECK or declaring it NOT ENFORCED would change the contract rather than fix this input.

Exercise 4

Attempt an orphan reference, then confirm the two valid children remain.

Worked solution
SAVEPOINT trial;
INSERT INTO lab_assets114 VALUES (103,'C',1,99);
-- Expected error: inspect it before running the recovery lines.
ROLLBACK TO SAVEPOINT trial;
RELEASE SAVEPOINT trial;
SELECT COUNT(*) FROM lab_assets114;

No department 99 exists. The foreign key should reject the orphan immediately; InnoDB does not defer this check to commit. The final count checks that no invalid trial was retained. A JOIN in a later report could hide an orphan but would not provide this storage protection.

Clean up the exact lab objects

Run cleanup only if these objects were created successfully by this lesson in the verified disposable database. Roll back row changes before dropping definitions. If setup stopped midway, inspect which lesson-owned objects exist and remove only those known creations. Do not use a broad database drop or disable foreign keys to simplify cleanup.

ROLLBACK;
DROP TABLE lab_assets114;
DROP TABLE lab_depts114;
SET SESSION sql_mode = @saved_mode114;

Pitfalls and summary

Engine, type compatibility, parent uniqueness, indexes, and enforcement settings belong in the integrity checklist. Re-enabling foreign_key_checks after bypassing it is not a substitute for validating preexisting rows. This lab never disables it. RESTRICT expresses the decision to block parent changes while dependents exist, rather than silently cascading them.

Test constraints with narrow invalid cases, verify the surviving baseline, and distinguish statement recovery from whole-transaction failure. Most importantly, keep ordinary DDL lifecycle separate from transactional row cleanup. A successful rollback is not evidence that the lab’s ordinary tables have disappeared.

Knowledge check

Question 1

Why does this foreign-key lab use ordinary rather than temporary tables?

  1. MySQL foreign keys cannot be defined on temporary tables
  2. Temporary InnoDB tables cannot contain primary keys
  3. Ordinary tables make CREATE TABLE rollbackable
  4. Temporary tables defer foreign-key checks until COMMIT
Answer and explanation

A. The documented foreign-key restriction excludes temporary parent and child tables.

Question 2

Why are both department columns INT UNSIGNED?

  1. The child may use any sign because only the parent type matters
  2. Their integer size and sign must be compatible for the foreign key
  3. Matching unsigned types enforce the relationship even without REFERENCES
  4. Matching types remove the need for a parent index
Answer and explanation

B. The matching integer definition satisfies a foreign-key compatibility requirement; keys and indexes remain separate.

Question 3

What does ROLLBACK remove in this lab before the DROP statements?

  1. Both table definitions because all DDL is transactional
  2. Only the most recent failed insert and no successful fixture rows
  3. The foreign-key definition but not the stored rows
  4. The transaction’s practice rows, while ordinary table definitions remain
Answer and explanation

D. The row transaction is rollbackable; ordinary CREATE TABLE definitions are not undone by that rollback.

Question 4

Why pair NOT NULL with a nonnegative CHECK on qty?

  1. NOT NULL supplies the nonnegative comparison automatically
  2. CHECK alone can accept an unknown result caused by NULL
  3. CHECK always rejects NULL but ignores negative integers
  4. The foreign key already makes qty non-NULL
Answer and explanation

B. Requiredness excludes NULL separately from the CHECK’s false-condition rejection.

Question 5

Which conclusion follows from a successful orphan-insert rejection?

  1. Every possible referential rule in the database has been verified
  2. A report JOIN would provide identical storage enforcement without a foreign key
  3. The tested foreign-key rule rejected that invalid reference under the recorded setup
  4. Changing foreign_key_checks later cannot alter enforcement
Answer and explanation

C. A negative test supports its specific rule and environment, not an unlimited integrity guarantee.

Dialect verification notes

The target is MySQL 8.4. Engine execution remains pending. SQLite was not used as a substitute for executing these dialect-specific scripts. Record actual server version, session settings, results, and errors when running the local lab. Python is not a learner prerequisite.

Primary references