SQL Constraints
📙 Welcome to SQL Constraints!
Hey there, new SQL learner! Imagine organizing a big toy box and making sure no toy gets lost or mixed up. Constraints are like special rules you set for your database tables to keep everything in order. They help stop mistakes, like adding a negative age or leaving a name blank. We’ll use a students table (with columns like id, name, and age) to show you how it works, step by step!
📘 What Are Constraints?
Constraints are like guardrails for your data. They are rules you add to columns in a table to:
- Prevent invalid data (e.g., no negative ages like -5).
- Make sure some data is unique (e.g., no two students with the same ID).
- Keep everything consistent across your database.
There are several types of constraints, like NOT NULL, UNIQUE, CHECK, and DEFAULT. Let’s explore each type with simple examples!
💡 Pro Tip: Add constraints when creating tables to catch mistakes early—like setting the rules before the game begins!
📘 NOT NULL Constraint (No Empty Spots!)
This rule makes sure a column always has a value—it can’t be empty (NULL). It’s perfect for things like names or IDs that you always need.
How It Works: If you mark a column as NOT NULL, you must fill it in when adding a new row. If you don’t, SQL will say, “Oops, you forgot something!”
Example:
- SQL Code
- Output
CREATE TABLE students (
id INT,
name VARCHAR(50) NOT NULL, -- Name must have a value
age INT
);
INSERT INTO students (id, name, age) VALUES (1, 'Alice', 20); -- This works!
-- This will fail: INSERT INTO students (id, age) VALUES (2, 21); -- No name!
| id | name | age |
|---|---|---|
| 1 | Alice | 20 |
What NOT to Do: Always use NOT NULL for critical fields like names or IDs—leaving them blank can mess up your records and make it data harder to track.
🔄 UNIQUE Constraint (No Doubles Allowed!)
This rule ensures that every value in a column is different—no duplicates. It’s great for things like email addresses or student IDs.
How It Works: If you try to add the same value twice (e.g., two students with the same email), SQL will stop you and say, “Hey, that’s already taken!”
Example:
- SQL Code
- Output
CREATE TABLE students (
id INT,
email VARCHAR(50) UNIQUE -- No two students can have the same email
);
INSERT INTO students (id, email) VALUES (1, 'alice@example.com'); -- Works!
-- This will fail: INSERT INTO students (id, email) VALUES (2, 'alice@example.com'); -- Duplicate!
| id | |
|---|---|
| 1 | alice@example.com |
What NOT to Do: Avoid using UNIQUE on columns that might repeat naturally, like ages (e.g., two 20-year-olds)—it’ll block valid data and cause errors!