smartyfy.mrindigi.com

Databases & SQL Master Course — 178. Relational Division

Lesson 178 Relational Division

Prerequisites and objectives

Complete Lesson 177 and review the earlier concepts named in this lesson. You will express “has every required item” using a missing-item test, contrast it with exact-set equality, and reason about an empty requirement set. Review EXISTS, correlated subqueries, primary keys, and NULL behavior. The fictional candidates are generic identifiers, not an automated selection system for real people.

Translate every into no missing requirement

Relational division is a name for questions such as which bundles contain every requested feature. SQL does not need a special division keyword to express the condition. A useful translation is: retain a candidate if there is no required item for which that candidate lacks a matching association. This directly describes a counterexample search.

Work from the candidate universe, not only the association table. Candidate C has no recorded skills but still exists as a candidate. Starting from associations would lose that identity before asking whether the requirements are empty. The universe of entities and the universe of required items are separate inputs to the question.

The association key prevents duplicate candidate-skill pairs. Required skills are also unique and non-NULL. Those constraints simplify both the logic and alternative counting solutions. Without them, raw row counts can mistake repeated evidence for coverage. A duplicate SQL record does not demonstrate a second required skill.

CREATE TABLE lab_candidate178(id TEXT PRIMARY KEY NOT NULL);
CREATE TABLE lab_required178(skill TEXT PRIMARY KEY NOT NULL);
CREATE TABLE lab_has178(candidate TEXT NOT NULL,skill TEXT NOT NULL,PRIMARY KEY(candidate,skill));
INSERT INTO lab_candidate178 VALUES('A'),('B'),('C');
INSERT INTO lab_required178 VALUES('SQL'),('Modeling');
INSERT INTO lab_has178 VALUES('A','SQL'),('A','Modeling'),('A','Python'),('B','SQL');
Expected coverage under two required skills
Candidate Required skills present Contains every requirement?
A SQL, Modeling Yes; extra Python is allowed
B SQL No; Modeling is missing
C None No; both are missing

Follow the correlated predicates inward

For each candidate, the outer NOT EXISTS asks whether any disqualifying required skill can be found. The inner NOT EXISTS checks whether a matching association is absent for that particular candidate and requirement. If one requirement is missing, the candidate is excluded; if no requirement is missing, the candidate survives.

Read each correlation aloud. The association’s candidate must equal the current candidate, and its skill must equal the current required skill. Omitting either comparison changes the meaning. A global SQL association held by someone else cannot satisfy C’s requirement, and any unrelated skill cannot satisfy Modeling.

Exercise 1

Find candidates containing all required skills.

Worked solution
-- Connection A
SELECT c.id FROM lab_candidate178 c WHERE NOT EXISTS (SELECT 1 FROM lab_required178 r WHERE NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND h.skill=r.skill)) ORDER BY c.id;

Only A has a matching association for both required rows. Its extra Python skill is irrelevant to this “at least the required set” question. B and C each have a missing requirement, so the nested anti-existence test finds a counterexample for them.

Exercise 2

Return the missing evidence instead of only a pass/fail answer.

Worked solution
-- Connection A
SELECT c.id,r.skill FROM lab_candidate178 c CROSS JOIN lab_required178 r WHERE NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND h.skill=r.skill) ORDER BY c.id,r.skill;

The diagnostic relation explains exclusions at candidate-requirement grain. It is often more useful for debugging a specification than a final list alone. Its three rows are missing associations, not three failed candidates; aggregating it requires an explicit change of grain.

Exercise 3

Evaluate the empty requirement set and restore the fixture.

Worked solution
-- Connection A
BEGIN;
DELETE FROM lab_required178;
SELECT c.id FROM lab_candidate178 c WHERE NOT EXISTS (SELECT 1 FROM lab_required178 r WHERE NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND h.skill=r.skill)) ORDER BY c.id;
ROLLBACK;

With no required items, no candidate has a missing requirement, so every candidate qualifies under universal logic. If a product should reject an empty request, enforce that separate input rule. Do not “fix” the query by accidentally dropping candidates without associations.

Exercise 4

Change the question to exactly the required set.

Worked solution
-- Connection A
SELECT c.id FROM lab_candidate178 c WHERE NOT EXISTS (SELECT 1 FROM lab_required178 r WHERE NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND h.skill=r.skill)) AND NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND NOT EXISTS (SELECT 1 FROM lab_required178 r WHERE r.skill=h.skill)) ORDER BY c.id;
BEGIN;
DELETE FROM lab_has178 WHERE candidate='A' AND skill='Python';
SELECT c.id FROM lab_candidate178 c WHERE NOT EXISTS (SELECT 1 FROM lab_required178 r WHERE NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND h.skill=r.skill)) AND NOT EXISTS (SELECT 1 FROM lab_has178 h WHERE h.candidate=c.id AND NOT EXISTS (SELECT 1 FROM lab_required178 r WHERE r.skill=h.skill)) ORDER BY c.id;
ROLLBACK;

Exact equality requires two directions: no missing requirement and no extra association. Initially A fails only the no-extras rule. Removing its extra skill in a rollback-only trial makes it an exact match without changing the required set.

Compare counting formulations carefully

A grouped alternative can count the distinct required skills matched by each candidate and compare that with the number of requirements. It must restrict counted items to the required set, handle duplicates intentionally, and preserve candidates when the required set is empty if that is the intended logic. COUNT of all associations is not equivalent.

For example, a bundle with SQL and two unrelated skills can have more rows than there are requirements while still lacking Modeling. Matching totals prove coverage only when the counted universe and uniqueness assumptions justify the inference. The nested missing-item formulation makes that universe particularly visible.

NULL identifiers would complicate equality-based matching because unknown is not true. This fixture rejects them at the schema boundary. A production system that admits unknown skills needs an explicit meaning for that state, rather than expecting NULL to serve as a wildcard for every requirement.

Test one complete candidate, one partial candidate, one with no associations, an extra association, and the empty requirement set. Also verify uniqueness enforcement. These edge cases reveal logical errors that a fixture containing only successful candidates cannot expose. Indexing the association key supports lookups, but a faster incorrect membership condition remains incorrect.

Pitfalls and summary

Separate contains-all from exactly-equal, define the candidate universe, and make the empty-set policy explicit. Search for missing requirements before reaching for complex counting. Use diagnostic missing rows to explain outcomes and verify the model with small counterexamples before optimizing it.

Knowledge check

Question 1

What does the inner NOT EXISTS identify?

  1. A skill missing from every candidate simultaneously
  2. Any extra skill held by the candidate
  3. A required skill missing for the current candidate
  4. Whether the candidate has more association rows than requirements
Answer and explanation

C. Both correlations bind the missing-evidence test to one candidate and one requirement.

Question 2

Why does A qualify despite having Python?

  1. Extra associations cancel missing requirements
  2. Any three associations satisfy any two required skills
  3. The query compares only total association counts
  4. The question requires at least all required skills, not exact equality
Answer and explanation

D. Contains-all permits extras; exact-set equality adds a separate no-extras condition.

Question 3

What happens when the required relation is empty?

  1. Only candidates with at least one association qualify
  2. Every candidate in the candidate universe qualifies
  3. No candidate qualifies under NOT EXISTS
  4. Only candidates with no associations qualify
Answer and explanation

B. There is no missing requirement; rejecting empty input would be an additional business rule.

Question 4

Why is counting all association rows unsafe?

  1. Unrelated or duplicate associations can inflate the count without covering requirements
  2. COUNT treats unrelated non-NULL skills as missing rather than counted
  3. Grouping automatically removes associations outside the required set
  4. A larger count proves exact-set equality
Answer and explanation

A. Counts must measure distinct matched requirements under explicit constraints.

Question 5

What extra condition changes contains-all to exact equality?

  1. The total association count must merely reach the requirement count
  2. The candidate must always have at least one association
  3. Extra associations must be ignored before testing equality
  4. The candidate must have no association outside the required set
Answer and explanation

D. Set equality requires no missing items and no extra items.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references