UPI Study › Courses › Database Programming › Free lessons › Lesson 2.7 Free with a free account
SQL Constraints: Enforcing Rules on Your Data
Database Programming · Chapter 2: Normalization and Data IntegritySection 2.7 · lesson 14 of 7610 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Data Definition Language (DDL): Concepts and Examples →← Foreign Keys in SQL: Linking Tables TogetherNext lesson: Data Definition Language (DDL): Concepts and Examples →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Use NOT NULL, UNIQUE, CHECK, and DEFAULT to protect stored data.
- Apply NOT NULL, UNIQUE, CHECK, and DEFAULT constraints to a table
- Explain how NULL interacts with CHECK conditions, defaults, and unique columns
- Write column-level rules and named table-level constraints
- Recognize common MySQL and SQL Server constraint error codes
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,211 words). Read along, or search it.
Opening Problem
An Import Script Bypasses the Website
A website rejects negative prices, but an import script writes directly to Lantern Books' database. Which rules still protect the stored rows? Stored constraints protect data across clients. This disposable catalog variant requires positive prices. Keep the canonical Notebook row, then try invented additions. Real results reveal what each rule does.
What Constraints Do
Stored Rules for Every Client
A constraint is a stored requirement. Inserts and updates must satisfy enabled rules, regardless of the client. Our ordinary SQLite statements use the default abort policy: a failing statement loses its own changes, while earlier successful statements remain. Other conflict policies and engines differ. Several statements do not automatically form one transaction. A primary key supplies row identity; a foreign key protects a relationship. The additional rules handle presence, uniqueness, conditions, and omitted values.
NOT NULL
Null Versus Empty Text
Null marks a missing or unknown value. It is neither zero nor an empty string, and not null rejects that missing marker. An omitted column can receive a valid default. Not null requires the resulting value, rather than explicitly supplied input. The second name is empty text, which is stored data. Rejecting it needs an additional condition. Run both attempts. Quote displays empty text as paired quotation marks. The null name fails, but the empty name is stored. Required presence and useful content are different rules.
UNIQUE
One Product per Catalog Code
Unique rejects repeated non-null values. Our positive-price catalog also requires a unique stock-keeping unit, abbreviated S K U. Several unique constraints can coexist with one primary key. A multi-column rule protects the combination, while individual columns may repeat. For nullable unique columns, SQLite and MySQL permit multiple nulls. SQL Server's ordinary single-column unique constraint permits one; not null removes that difference. Run the repeated catalog-code attempt. Its different product identifier cannot bypass the unique rule. The duplicate code is rejected. Notebook remains, with independent protection for its identity and catalog code.
CHECK
Conditions, Unknown Results, and Null Prices
Check evaluates a condition. A positive price makes this test true; a negative price makes it false. A simple comparison with null yields unknown, which check permits. To forbid missing prices, combine check with not null. An is null test can give a definite result, so null does not make every possible condition unknown. Run this separate nullable-price sandbox. Unknown displays its stored null marker. The negative price fails; positive and null prices remain. Check alone does not require a price.
DEFAULT
Omitted Stock Starts at Zero
Default supplies a value when a column is omitted. Bookmark omits stock, so its stock starts at zero. Writing null explicitly does not request the ordinary default. The second insert writes null stock, which conflicts with the required-value rule. A default is a fallback, not a validity test. Its supplied value still has to satisfy applicable constraints. Run both stock cases. Each attempt is a separate ordinary statement. Bookmark gets zero; explicit null fails. Notebook retains stock thirty, because defaults do not overwrite existing values.
Placement
Column-Level and Table-Level Rules
Column-level rules are written beside one column. Product name is required, while stock is required and defaults to zero. Table-level rules follow the column list. A multi-column unique rule, such as cart and product together, belongs in that form. A cross-column check compares sale price with regular price. Table-level placement is portable; SQLite permits cross-column checks beside a column too. We use numeric values here without claiming fixed decimal scale. SQLite does not enforce declared decimal scale or varchar length like rigidly typed engines.
Named Constraints
Sale Price Above Regular Price
Name important rules by purpose: primary key, foreign key, unique, check, or a named default where supported. Prefixes help locate rules. SQLite can name check failures; other diagnostics identify columns or give generic wording. Here, a sale price above the regular price violates the named comparison. Null sale price remains valid unless a separate required-value rule forbids it. Run the update. Read the named check before deciding what data to correct. The sale check fails. Notebook still has no sale price; the invalid update did not overwrite its valid row.
Vendor Errors
Null and Duplicate Key Error Codes
For vendor error recognition, MySQL reports a null violation as ten forty-eight; SQL Server commonly reports five fifteen. Duplicate keys commonly use ten sixty-two in MySQL, or twenty-six twenty-seven in SQL Server. Read the key name to distinguish primary from unique. These numbers are reference information, rather than local runs. MySQL calls its primary key PRIMARY; SQL Server allows a chosen primary-key constraint name.
Vendor Errors
Check and Foreign Key Error Codes
MySQL reports a check violation as thirty-eight nineteen. SQL Server commonly uses five forty-seven, so read whether the message names check or foreign key. A missing parent commonly produces fourteen fifty-two in MySQL, while SQL Server again uses five forty-seven. The rule kind matters more than memorizing a number. MySQL began enforcing check constraints in version eight point zero point sixteen. Constraints can be disabled or not enforced in supporting systems; verify their active status.
Naming and Reading
Prefixes and Reading Errors in Order
Use concise prefixes such as p k, f k, u q, and c k, followed by a table and purpose. SQL Server can name a default constraint; MySQL does not offer that same named-default object. Not null is a column property in those systems. Read an error in order: identify the rule kind, locate the rule or column, inspect the offending values, and correct the data. Do not weaken a sound rule simply to silence an error. A genuine rule change deserves a deliberate schema decision.
Layered Rules
Several Rules Protect One Order
Several rules can protect one row. This separate order sandbox requires a customer, supplies Pending status, and limits status to approved values. The foreign key checks existence. Not null separately requires a supplied or validly filled customer reference. A misspelled status would fail check. These rules close different gaps. Run the valid and missing-parent attempts. The status default still participates in validation. Only the valid order remains, with Pending supplied. A valid default cannot excuse the absent parent.
Quick Check
Explicit Null Meets Default and Check
A new seats table has a default spare count and a nonnegative check, but no not-null rule. The insert explicitly supplies null. Will the query display the default, display missing, or produce a check error? Pause, and predict how these two rules combine. Missing is the answer. Explicit null does not request the default, and the comparison evaluates to unknown rather than false. Run the combined-rule example. Coalesce will display missing if the row's spare value really remains null. Missing appears. The default option confuses omitted input with explicit null; the error option assumes check rejects unknown.
Quick Check
A Two-Row Insert with One Bad Range
A fresh range table receives two tuples in one ordinary insert. The first range is ordered correctly; the second has its low value above its high value. How many rows remain after the statement: two, one, or zero? Pause, and predict the result under the default SQLite conflict policy. Zero rows remain. The ordinary abort policy backs out the whole failing statement, including the first tuple that would have passed alone. Run the two-tuple insert, then count the stored rows. The named range check identifies the failed requirement. The count is zero. Keeping one tuple would describe a different conflict policy, and keeping both would violate the declared range rule.
Key Takeaways
Put Important Rules in the Database
Use not null for required values, unique for distinct identities, and check for valid conditions. Combine them where their jobs differ. Default fills omitted values. Explicit null and unknown comparisons need separate attention, especially when a field must be present. Put important rules in the database, name them clearly where supported, and read real errors before correcting the data.
About Database Programming at UPI Study
Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About SQL Constraints: Enforcing Rules on Your Data
What are constraints in SQL?
Does a CHECK constraint allow NULL values?
Does a DEFAULT value apply when you insert NULL?
Can a UNIQUE column contain NULL values?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Database Programming.
76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →