Constraints and Data Integrity
# CHAPTER 19
Constraints and Data Integrity
1. Introduction
Web applications are full of bugs. A frontend form might accidentally allow a user to submit a negative age (-5). A PHP script might fail to capture an email address and try to save a blank row. If the database blindly accepts this garbage data, the entire application will eventually break. The database must act as the ultimate, impenetrable wall of defense. In this chapter, we will master Constraints—the strict mathematical rules we attach to columns to guarantee absolute Data Integrity.2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the purpose of Data Integrity constraints.
-
Prevent blank data using
NOT NULL.
-
Prevent duplicate data using
UNIQUE.
-
Provide fallback data using
DEFAULT.
-
Enforce business logic using
CHECKconstraints.
3. The NOT NULL Constraint
By default, MySQL allows any column to be completely empty (NULL). If you have a users table, a user without an email address is useless to the business.
The NOT NULL constraint forces the column to reject any INSERT or UPDATE that attempts to leave it blank.
*If a PHP script attempts INSERT INTO users (bio) VALUES ('Hello');, MySQL will immediately crash the script with an error because username was omitted.*
4. The UNIQUE Constraint
As covered in Chapter 12, Primary Keys are automatically unique. But what if you need a *second* column to be unique, like an Email or a Driver's License number?
5. The DEFAULT Constraint
Sometimes, users skip optional form fields, but you want the database to automatically fill in a standard fallback value instead of leaving it NULL.
*If you run INSERT INTO orders (productname) VALUES ('Laptop');, MySQL will flawlessly fill in the status and orderdate without you typing them!*
6. The CHECK Constraint (Business Logic)
This is the ultimate defense mechanism. The CHECK constraint allows you to write custom mathematical rules that the data must pass before it is allowed onto the hard drive.
*If a hacker manipulates a form to submit a price of -50.00, the PHP might miss it, but the MySQL CHECK constraint will instantly block it and protect your finances!*
7. Adding Constraints to Existing Tables
You don't need to drop your table to add rules. You can use theALTER TABLE command.
8. Common Mistakes
-
Trusting Frontend Validation Only: Beginners often put
requiredtags on their HTML forms and assume the data is safe. HTML can be bypassed in 3 seconds using browser dev tools. Backend PHP validation is better, but bugs happen. Database Constraints are the only guarantee of data integrity.
-
Overusing
NOT NULL: Don't putNOT NULLon columns that genuinely might not be known yet (likecancellationdateon a fresh order). Only use it for absolutely critical required data.
9. Best Practices
-
Naming Constraints: When using
CHECK, always name your constraints usingCONSTRAINT name CHECK (...). If you don't provide a name, MySQL generates a random gibberish name (likechk1a2b). If the constraint blocks an insertion in production, the error log will say "Constraint chk1a2b failed", and you will have no idea what rule was broken!
10. Exercises
-
1.
Write the SQL syntax to create a
votestable with anagecolumn that enforces aCHECKconstraint ensuring the user is at least 18 years old.
-
2.
How does
DEFAULT CURRENTTIMESTAMPsimplify your backend application code?
11. MCQ Quiz with Answers
If an E-Commerce table has a price column, which constraint is specifically designed to prevent negative numbers from being inserted into the database?
Why should database constraints be implemented even if your web application's frontend (HTML/JS) already validates the user's input?
12. Interview Questions
-
Q: Explain the difference between a
PRIMARY KEYconstraint and aUNIQUEconstraint. Can a table contain multiple of both?
-
Q: Describe a business scenario where utilizing a
DEFAULTconstraint significantly cleans up and simplifies the backendINSERTlogic.
13. FAQs
Q: Can I use aCHECK constraint to compare data against another table?
A: No, standard CHECK constraints can only evaluate data within the exact same row being inserted. To check rules against other tables, you must use "Triggers" (which we cover in Chapter 22).
14. Summary
A database is only as valuable as the accuracy of the data within it. By enforcingNOT NULL, UNIQUE, DEFAULT, and CHECK constraints, you shift the responsibility of data validation deep into the database engine, creating an unbreakable architecture that actively rejects human error and software bugs.