Skip to main content
MySQL Basics
CHAPTER 19 Beginner

Constraints and Data Integrity

Updated: May 16, 2026
5 min read

# 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 CHECK constraints.

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.
sql
12345
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,    -- This MUST be provided!
    bio TEXT                          -- This is allowed to be empty (NULL).
);

*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?
sql
12345
CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(150) NOT NULL UNIQUE,  -- Cannot be blank, Cannot be duplicated!
    ssn VARCHAR(11) UNIQUE               -- Cannot be duplicated
);

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.
sql
123456
CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    status VARCHAR(20) DEFAULT 'Pending',   -- Automatically sets to 'Pending'
    order_date DATETIME DEFAULT CURRENT_TIMESTAMP -- Automatically grabs the current server time!
);

*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.
sql
123456789101112
CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    discount_percent INT DEFAULT 0,
    
    -- RULE 1: Price can never be negative
    CONSTRAINT chk_price CHECK (price >= 0),
    
    -- RULE 2: Discount must be between 0 and 100
    CONSTRAINT chk_discount CHECK (discount_percent >= 0 AND discount_percent <= 100)
);

*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 the ALTER TABLE command.
sql
1234567
-- Add a DEFAULT rule to an existing column
ALTER TABLE users 
ALTER COLUMN role SET DEFAULT &#039;Subscriber';

-- Add a UNIQUE constraint
ALTER TABLE users 
ADD UNIQUE (username);

8. Common Mistakes

  • Trusting Frontend Validation Only: Beginners often put required tags 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 put NOT NULL on columns that genuinely might not be known yet (like cancellationdate on a fresh order). Only use it for absolutely critical required data.

9. Best Practices

  • Naming Constraints: When using CHECK, always name your constraints using CONSTRAINT name CHECK (...). If you don't provide a name, MySQL generates a random gibberish name (like chk1a2b). 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. 1. Write the SQL syntax to create a votes table with an age column that enforces a CHECK constraint ensuring the user is at least 18 years old.
  1. 2. How does DEFAULT CURRENTTIMESTAMP simplify your backend application code?

11. MCQ Quiz with Answers

Question 1

If an E-Commerce table has a price column, which constraint is specifically designed to prevent negative numbers from being inserted into the database?

Question 2

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 KEY constraint and a UNIQUE constraint. Can a table contain multiple of both?
  • Q: Describe a business scenario where utilizing a DEFAULT constraint significantly cleans up and simplifies the backend INSERT logic.

13. FAQs

Q: Can I use a CHECK 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 enforcing NOT 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.

15. Next Chapter Recommendation

Our data rules are perfectly strict. But what happens if we need to transfer $500 from Account A to Account B? We deduct $500 from A, but before we can add it to B, the server loses power! The $500 vanishes forever! In Chapter 20: Transactions and ACID Properties, we learn how to make multiple SQL commands execute as an unbreakable, all-or-nothing unit.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·