Skip to main content
SQL Fundamentals
CHAPTER 14 Beginner

SQL Constraints Explained | Primary Key, UNIQUE, NOT NULL

Updated: May 16, 2026
15 min read

# CHAPTER 14

Primary Keys and Constraints

1. Introduction

A database is only as valuable as the integrity of its data. If an E-Commerce database allows two different users to register with the exact same email address, or allows an order to be placed with a negative price, the entire application will collapse in chaos. Application code (like PHP or Node.js) has bugs. The database must be the final, unbreakable wall of defense. In SQL, we build these walls using Constraints. In this chapter, we will master the absolute most important concept in database architecture: The Primary Key.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the definition and critical necessity of Constraints.
  • Implement the PRIMARY KEY to uniquely identify rows.
  • Utilize AUTO_INCREMENT / SERIAL to generate IDs mathematically.
  • Prevent missing data using NOT NULL.
  • Prevent duplicate data using the UNIQUE constraint.
  • Set fallback data using DEFAULT.

3. The PRIMARY KEY (The Fingerprint)

Imagine a table with 50 employees named "John Smith". How do you tell the database to update the salary for a specific John Smith without accidentally updating all 50 of them? Every table must have one column that acts as a mathematically guaranteed, globally unique fingerprint for that row. This is the PRIMARY KEY.

A Primary Key has two strict rules:

  1. 1. It must be absolutely UNIQUE (No two rows can have the same key).
  1. 2. It cannot be NULL (Every row must possess a key).

sql
12345
CREATE TABLE users (
    -- Designate the 'id' column as the Primary Key
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

4. Auto-Incrementing the Primary Key

You should never manually type the ID number when writing an INSERT statement (INSERT INTO users VALUES (1)). If two users register on the website at the exact same millisecond, the PHP server might assign them both ID #500, causing a fatal database crash. The database must generate the number automatically!
  • MySQL: AUTO_INCREMENT
  • PostgreSQL: SERIAL
sql
12345
-- MySQL Syntax for a perfect ID column!
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50)
);

*(Now, when you insert data, you simply ignore the ID column. SQL handles the math automatically: 1, 2, 3...)*

5. The NOT NULL Constraint

By default, if you don't provide data for a column during an INSERT, SQL happily fills it with NULL (Empty). If an email is missing, the user cannot log in. We block this using NOT NULL.
sql
1234
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(100) NOT NULL -- If an insert lacks an email, SQL throws a fatal error!
);

6. The UNIQUE Constraint

The Primary Key is unique, but what if you have other columns that also must be unique? A user's username or email_address cannot be shared by two people.
sql
1234
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(100) NOT NULL UNIQUE -- Cannot be empty, and cannot be a duplicate!
);

7. The DEFAULT Constraint

If a user registers, their account shouldn't be verified immediately. Instead of forcing the PHP code to manually insert is_verified = FALSE, we can tell SQL to set a default fallback value.
sql
12345
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(100) NOT NULL UNIQUE,
    is_verified BOOLEAN DEFAULT FALSE -- Automatically FALSE unless specified otherwise!
);

8. Mini Project: The Bulletproof User Schema

Let's combine all of our constraints to build a production-grade, enterprise-ready user table.
sql
1234567891011121314151617
CREATE TABLE secure_users (
    -- The Mathematical Fingerprint
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    
    -- Mandatory, Unique identifiers
    username VARCHAR(30) NOT NULL UNIQUE,
    email VARCHAR(150) NOT NULL UNIQUE,
    
    -- Optional data (No constraints)
    bio TEXT,
    
    -- Mandatory data with a secure fallback
    account_status VARCHAR(20) NOT NULL DEFAULT 'Pending',
    
    -- Auto-timestamping the registration
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

9. Common Mistakes

  • Using Emails or Names as Primary Keys: A beginner might say "Emails are unique, let's make email the Primary Key!" This is a terrible architectural decision. If the user changes their email address, the Primary Key changes, breaking all relationships to other tables. Primary Keys should be meaningless, auto-incrementing Integers that never change.

10. Best Practices

  • The Check Constraint: Some databases (like PostgreSQL and modern MySQL) support CHECK. You can add age INT CHECK (age >= 18) to physically block minors from being inserted into the database!

11. Exercises

  1. 1. What are the two strict mathematical rules that define a PRIMARY KEY?
  1. 2. What constraint tells SQL to automatically insert a specific value if the developer forgets to provide one during an INSERT?

12. SQL Challenges

Write the DDL to create a products table. The productid must be an auto-incrementing primary key. The skucode must be text, mandatory, and strictly unique. The price must be a decimal that defaults to 0.00.
sql
12345
CREATE TABLE products (
    product_id INT AUTO_INCREMENT PRIMARY KEY,
    sku_code VARCHAR(50) NOT NULL UNIQUE,
    price DECIMAL(10, 2) DEFAULT 0.00
);

13. MCQ Quiz with Answers

Question 1

What is the fundamental architectural purpose of a PRIMARY KEY in a relational database table?

Question 2

When defining a table schema, a developer applies the UNIQUE and NOT NULL constraints to the username column. What happens if a backend application attempts to INSERT a new row without providing a username?

14. Interview Questions

  • Q: Explain the philosophical difference between the PRIMARY KEY constraint and the UNIQUE constraint. Can a table have multiple UNIQUE columns? Can a table have multiple PRIMARY KEY columns?
  • Q: A junior developer manually calculates the id for new user inserts by querying SELECT MAX(id) + 1. Explain why this is catastrophically dangerous in a highly concurrent web application, and explain how the AUTOINCREMENT/SERIAL features solve it.

15. FAQs

Q: Can a Primary Key be made of two columns? A: Yes! This is called a Composite Primary Key. In a Many-to-Many bridge table (like student
classes), the combination of (studentid, classid) acts as the primary key. We will cover this in the Relationships chapter!

16. Summary

Your database is now an impenetrable fortress. By defining explicit PRIMARY KEYS for mathematical identification, locking down mandatory fields with NOT NULL, preventing duplicates with UNIQUE, and automating defaults, you guarantee that no bug in the application code can ever corrupt the structural integrity of your tables.

17. Next Chapter Recommendation

We have perfected the single table. But Relational Databases are built on *relationships*. How does the orders table know which user placed the order? In Chapter 15: Foreign Keys and Relationships, we will finally connect our tables together using structural anchors.

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: ·