Create a Table That Protects Its Data · practice
Supply the Usual Loan Period
Most items in the lending catalog can be borrowed for seven days. A special item may have a different period, but making every ordinary record repeat 7 invites an avoidable mistake. The table can remember the usual choice in one place, so every program that uses it gets the same answer.
We want these three cases to behave differently:
loan_days | What SQLite should do |
|---|---|
| No value is supplied | Save 7 |
14 is supplied | Save 14 |
NULL is supplied | Refuse the record |
The table needs a usual value for the first case while keeping its protection from missing data in the third.
Add the usual value
Open schema.sql and find the current declaration:
loan_days INTEGER NOT NULL
Add the usual value without removing the rule that is already there:
loan_days INTEGER NOT NULL DEFAULT 7
Press Run and find that line in the complete table definition SQLite prints.
DEFAULT tells SQLite what to store when a new record leaves that column out. It does not replace a value that was supplied. An item given 14 loan days keeps 14.
Leaving out a column and supplying NULL are not the same request. Leaving out loan_days says, in effect, “use the table’s usual value.” Supplying NULL explicitly says that the value is missing. The existing NOT NULL rule refuses that missing value, so keep both NOT NULL and DEFAULT 7 on the line.
This distinction matters when a program creates a record. It can leave the decision to the table, or it can deliberately supply a different period. It cannot use NULL as another spelling of the default.
Once the new declaration loads, select Submit and compare the results with the three cases at the top of the lesson. An omitted loan period should become 7, a supplied value such as 14 should stay 14, and an explicit NULL should still be refused.
This default saves repeated work, but it does not decide which supplied numbers make sense. The table would still accept 0 or -2 as a loan period. In the next lesson, you will add a separate rule for that.
Task
Open schema.sql and give loan_days a default 7. Keep its NOT NULL rule.
Press Run and check that the table definition contains both rules. Then submit your schema. Omitting loan_days must store 7, supplying a positive value must preserve that value, and explicitly supplying NULL must still be refused.