topskill.dev
CoursesTracks
0
All courses/Introduction to SQLProject: keep the revised plan, reject an add-on
Change data safely and complete an allocation project
11 / 12
← Introduction to SQL
○Read rows with SELECT○Exercise: a lending-desk list○Name a result column with AS○Exercise: Name a result column with AS○Calculate a result with arithmetic○Exercise: Calculate a result with arithmetic○Remove duplicate result rows○Exercise: the category menu○Filter rows with WHERE○Exercise: Filter rows with WHERE○Require both conditions with AND○Exercise: Require both conditions with AND○Accept either condition with OR○Exercise: Accept either condition with OR○Reverse a known condition with NOT○Exercise: Reverse a known condition with NOT✦Module Quiz
○Recognize missing values with IS NULL○Exercise: gear without a note○Match an allowed list with IN○Exercise: Match an allowed list with IN○Select an inclusive range with BETWEEN○Exercise: Select an inclusive range with BETWEEN○Find text with LIKE○Exercise: names containing a space○Sort rows with an explicit tie-breaker○Exercise: Sort rows with an explicit tie-breaker○Take a bounded result with LIMIT○Exercise: Take a bounded result with LIMIT✦Module Quiz
○Count rows and known values with COUNT○Exercise: Count rows and known values with COUNT○Add known values with SUM○Exercise: Add known values with SUM○Calculate a mean with AVG○Exercise: Calculate a mean with AVG○Find a minimum with MIN○Exercise: Find a minimum with MIN○Find a maximum with MAX○Exercise: Find a maximum with MAX○Make one summary per group○Exercise: category totals○Filter groups with HAVING○Exercise: categories with enough stock✦Module Quiz
○Match related rows with INNER JOIN○Exercise: who booked each session○Keep unmatched rows with LEFT JOIN○Exercise: makers with no bookings○Reconcile two lists with FULL JOIN○Exercise: two attendance sheets○Read one table in two roles with a self join○Exercise: a mentor directory○Generate a small schedule with CROSS JOIN○Exercise: bench and shift combinations✦Module Quiz
○Create tables with purposeful data types○Exercise: a storage-bin table○Identify a row with PRIMARY KEY○Exercise: Identify a row with PRIMARY KEY○Require a value with NOT NULL○Exercise: Require a value with NOT NULL○Prevent repeated known values with UNIQUE○Exercise: Prevent repeated known values with UNIQUE○Validate a condition with CHECK○Exercise: Validate a condition with CHECK○Supply an omitted value with DEFAULT○Exercise: Supply an omitted value with DEFAULT○Require a matching parent with a foreign key○Exercise: Require a matching parent with a foreign key○Identify a relationship with a composite key○Exercise: Identify a relationship with a composite key○Insert rows with an explicit column list○Exercise: register two tool kits○Add a column with ALTER TABLE○Exercise: Add a column with ALTER TABLE✦Module Quiz
○Rename a column without replacing its values○Exercise: Rename a column without replacing its values○Remove one column with DROP COLUMN○Exercise: Remove one column with DROP COLUMN○Remove a table with DROP TABLE○Exercise: Remove a table with DROP TABLE○Avoid repeating groups in first normal form○Exercise: Avoid repeating groups in first normal form○Separate facts that depend on part of a key○Exercise: Separate facts that depend on part of a key○Separate indirectly dependent facts○Exercise: Separate indirectly dependent facts○Report a many-to-many relationship○Exercise: Report a many-to-many relationship○Project: build the people register○Project: add the workshop catalog○Project: connect people to workshops✦Module Quiz
○Update the rows you intend○Exercise: repair one fee○Delete selected rows, not the table○Exercise: retire one kit○Commit a unit of work or roll it back○Exercise: cancel a mistaken change○Undo a later part with SAVEPOINT○Exercise: keep the correction, undo the trial○Project: record an allocation atomically○Project: cancel the recorded allocation●Project: keep the revised plan, reject an add-on✦Module Quiz
○Use a scalar subquery as a value○Exercise: Use a scalar subquery as a value○Use a subquery as an IN list○Exercise: Use a subquery as an IN list○Read a subquery as a table○Exercise: Read a subquery as a table○Ask whether a related row exists○Exercise: makers who have bookings○Combine distinct rows with UNION○Exercise: Combine distinct rows with UNION○Keep every occurrence with UNION ALL○Exercise: Keep every occurrence with UNION ALL○Keep shared rows with INTERSECT○Exercise: Keep shared rows with INTERSECT○Subtract one result with EXCEPT○Exercise: Subtract one result with EXCEPT○Choose a value with CASE○Exercise: Choose a value with CASE○Display a fallback with COALESCE○Exercise: Display a fallback with COALESCE✦Module Quiz
○Trim surrounding spaces with TRIM○Exercise: Trim surrounding spaces with TRIM○Normalize letter case with LOWER○Exercise: Normalize letter case with LOWER○Make an uppercase label with UPPER○Exercise: Make an uppercase label with UPPER○Join text values with concatenation○Exercise: Join text values with concatenation○Count characters with CHAR_LENGTH○Exercise: Count characters with CHAR_LENGTH○Extract part of a value with SUBSTRING○Exercise: Extract part of a value with SUBSTRING○Round numeric output with ROUND○Exercise: Round numeric output with ROUND○Measure a magnitude with ABS○Exercise: Measure a magnitude with ABS○Round a packing count upward with CEIL○Exercise: Round a packing count upward with CEIL○Convert a value with CAST○Exercise: Convert a value with CAST✦Module Quiz
○Calculate calendar days between dates○Exercise: Calculate calendar days between dates○Filter a whole calendar period○Exercise: Filter a whole calendar period✦Module Quiz
○Name a reusable query with a view○Exercise: a ready gear view○Create an index without changing a result○Exercise: Create an index without changing a result○Read a query plan with EXPLAIN○Exercise: Read a query plan with EXPLAIN○Give a query stage a name with WITH○Exercise: summarize before filtering○Keep detail rows while calculating a rank○Exercise: rank gear within each category○Share a business rank across ties○Exercise: Share a business rank across ties○Count distinct ranked levels○Exercise: Count distinct ranked levels○Keep application input separate from SQL structure○Give a database account only the access it needs○Plan and test database recovery✦Module Quiz

Project: keep the revised plan, reject an add-on

The seed restores the completed cancellation from stage 2. Both original stock counts are back and allocations is empty. The revised plan reserves two Paint packs. Someone also suggests adding a Repair pack, but that suggestion is withdrawn before commit.

Data model

Exercise data

These tables are already loaded at the start of this lesson.

allocations

One row represents one reservation of supply packs.

Field / SQL typeMeaningRules
allocation_id · integerIdentifier of the reservation.Primary key. Required; cannot be NULL.
supply_id · integerRequired reference to the reserved supply kind.Required; cannot be NULL. Foreign key to supplies.supply_id.
quantity · integerWhole-number count of packs reserved by this allocation.Required; cannot be NULL. Check: quantity > 0.

supplies

One row represents one kind of supply pack, not one physical pack.

Field / SQL typeMeaningRules
supply_id · integerIdentifier of the supply kind.Primary key. Required; cannot be NULL.
name · textName of the supply kind.Required; cannot be NULL.
available · integerWhole-number count of packs of this kind still unallocated.Required; cannot be NULL. Check: available >= 0.

Stock counts and allocation quantities require coordinated writes; the constraints do not automatically reconcile them.

Relationship map

allocations.supply_id matches supplies.supply_id. One supplies row can have zero or many matching allocations rows; each allocations row must reference exactly one existing parent. This is a declared foreign key.

Joining child detail repeats the parent fields once per matching child. An inner join omits unmatched rows; a left join keeps unmatched rows from its left input with NULLs for the missing side. Those result NULLs are separate from missing values stored in a real row.

State for this lesson

The seed restores the completed cancellation: available stock is 10 Repair packs and 6 Paint packs, and allocations is empty. The prior SQL in the seed reconstructs this state before the new stage.

Record the wanted allocation first, then create a savepoint. Try the optional allocation after it, roll back only that later part, and commit the remaining work. The final report must retain allocation 101 for Paint packs and no allocation for Repair packs.

All the syntax comes from earlier lessons. The challenge is choosing the boundary: the savepoint belongs after the two statements that make the valid allocation, not between them. Otherwise rolling back could keep a stock deduction without its matching allocation.

Submit compares the final state and cannot inspect the transaction history. Read your sequence once more to confirm that the optional pair of writes really sits after the savepoint. You have now practiced an allocation, its cancellation, and a revised plan without changing the underlying schema.

Restored starting state

This read-only setup runs before your SQL. Add only the new stage in script.sql.

sql
CREATE TABLE supplies (
  supply_id integer PRIMARY KEY,
  name text NOT NULL,
  available integer NOT NULL CHECK (available >= 0)
);
CREATE TABLE allocations (
  allocation_id integer PRIMARY KEY,
  supply_id integer NOT NULL REFERENCES supplies(supply_id),
  quantity integer NOT NULL CHECK (quantity > 0)
);
INSERT INTO supplies VALUES (1,'Repair packs',10),(2,'Paint packs',6);
BEGIN;
UPDATE supplies SET available = available - 3 WHERE supply_id = 1;
INSERT INTO allocations VALUES (100,1,3);
COMMIT;
BEGIN;
UPDATE supplies SET available = available + 3 WHERE supply_id = 1;
DELETE FROM allocations WHERE allocation_id = 100;
COMMIT;

Edit script.sql, use Run to inspect the result, then Submit.

Your Task

  1. In one transaction, subtract 2 from supply_id 2 and insert (101,2,2). Savepoint core_allocation; then subtract 1 from supply_id 1 and insert (102,1,1). Roll back to the savepoint and commit. Return supply_id, available, allocation_id, quantity with the same LEFT JOIN and ordering.

Result to aim for

supply_idavailableallocation_idquantity
110NULLNULL
241012
Hint 1
1 / 1
HINT 1

A savepoint protects earlier work only when both of its related writes precede it.

Take the Quiz →
Files
  • ⋄script.sql
Loading editor…
Press Run to execute your code.