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 KEYto uniquely identify rows.
-
Utilize
AUTO_INCREMENT/SERIALto generate IDs mathematically.
-
Prevent missing data using
NOT NULL.
-
Prevent duplicate data using the
UNIQUEconstraint.
-
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.
It must be absolutely
UNIQUE(No two rows can have the same key).
-
2.
It cannot be
NULL(Every row must possess a key).
sql
4. Auto-Incrementing the Primary Key
You should never manually type the ID number when writing anINSERT 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
*(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
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
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
8. Mini Project: The Bulletproof User Schema
Let's combine all of our constraints to build a production-grade, enterprise-ready user table.
sql
9. Common Mistakes
-
Using Emails or Names as Primary Keys: A beginner might say "Emails are unique, let's make
emailthe 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 addage INT CHECK (age >= 18)to physically block minors from being inserted into the database!
11. Exercises
-
1.
What are the two strict mathematical rules that define a
PRIMARY KEY?
-
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 aproducts 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
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 KEYconstraint and theUNIQUEconstraint. Can a table have multipleUNIQUEcolumns? Can a table have multiplePRIMARY KEYcolumns?
-
Q: A junior developer manually calculates the
idfor new user inserts by queryingSELECT MAX(id) + 1. Explain why this is catastrophically dangerous in a highly concurrent web application, and explain how theAUTOINCREMENT/SERIALfeatures 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 (likestudentclasses), 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 explicitPRIMARY 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 theorders table know which user placed the order? In Chapter 15: Foreign Keys and Relationships, we will finally connect our tables together using structural anchors.