SQL Flow Field Guide

Design related tables with enforceable rules

Choose keys and constraints that make invalid application data fail at the database boundary.

What you are trying to do

A work tracking service stores teams and tasks. A task must belong to a real team, have a unique task number, and never have a negative estimate.

Work through it

  1. Read the table definitions from the parent keys to the dependent rows.
  2. Trace the primary key, unique key, foreign key, and check rule to the data each one protects.
  3. Compare the valid insert with the deliberately invalid estimate. The TRY/CATCH reports the constraint error without stopping the lab.
  4. Confirm that only the two valid tasks remain, then remove both local tables.
  5. These are session local tables. The script does not create or change a permanent object.

Check your work

The constraint check returns ErrorNumber 547. The final result has exactly two rows: task 101 for team 1 with 5 points, and task 102 for team 2 with 8 points. TaskId is unique, TeamId refers to an existing team, and Points is nonnegative.

Practice SQL

Open in SQL Flow
CREATE TABLE #Team (TeamId int NOT NULL PRIMARY KEY, TeamName nvarchar(30) NOT NULL UNIQUE);
CREATE TABLE #WorkItem (TaskId int NOT NULL PRIMARY KEY, TeamId int NOT NULL, Points int NOT NULL CHECK (Points >= 0), FOREIGN KEY (TeamId) REFERENCES #Team (TeamId));
INSERT INTO #Team (TeamId, TeamName) VALUES (1, N'Platform'), (2, N'Care');
INSERT INTO #WorkItem (TaskId, TeamId, Points) VALUES (101, 1, 5), (102, 2, 8);
BEGIN TRY
    INSERT INTO #WorkItem (TaskId, TeamId, Points) VALUES (103, 1, -1);
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
SELECT w.TaskId, t.TeamName, w.Points FROM #WorkItem AS w INNER JOIN #Team AS t ON t.TeamId = w.TeamId ORDER BY w.TaskId;
DROP TABLE #WorkItem;
DROP TABLE #Team;

Knowledge check

Commands in this lesson

Next lesson Keep the intended row grain across joins