SQL Constraints: Enforcing Rules on Your Data, Explained

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

← 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 →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

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.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Constraints are rules declared on a table that the database itself enforces for any client that inserts or updates data. Common kinds include NOT NULL, UNIQUE, CHECK, PRIMARY KEY, and FOREIGN KEY, and DEFAULT supplies a value for an omitted column. Because the rules live in the database, an import script cannot skip a check that a website form performs. Some systems let constraints be disabled, so verify they are active.
Does a CHECK constraint allow NULL values?
Yes, for a simple comparison: a CHECK constraint rejects a row when its condition is false, and comparing NULL yields unknown, which passes. So CHECK (price > 0) still accepts a missing price. To forbid missing values, add NOT NULL, or write a condition using IS NOT NULL. MySQL enforces CHECK constraints from version 8.0.16; earlier versions parsed the clause but ignored it.
Does a DEFAULT value apply when you insert NULL?
Generally no: a default fills a column that the INSERT leaves out, while an explicit NULL asks to store NULL. If the column is also NOT NULL, that explicit NULL is normally rejected, and if the column allows nulls, NULL is stored. A default is a fallback, not a validity test, so its value must still satisfy other constraints, and it does not overwrite a value already stored in a row.
Can a UNIQUE column contain NULL values?
Yes, a nullable UNIQUE column can hold nulls, but systems differ on how many. MySQL and SQLite allow several NULL values in an ordinary unique column, while SQL Server's ordinary single-column UNIQUE constraint allows one. Repeated non-null values are rejected in all three. An empty string is a stored value rather than a null, so two empty strings count as duplicates. Add NOT NULL when every row needs a value.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Database Programming
3 credits · NCCRS
Enroll →