SQL Constraints: NOT NULL & UNIQUE – Keeping Your Data Clean & Reliable

SQL constraints help you control your data, just like rules in a game. Two of the most common ones are NOT NULL and UNIQUE.


Quick Syntax


CREATE TABLE table_name (
    column1 datatype CONSTRAINT_NAME,
    column2 datatype CONSTRAINT_NAME,
    ...
);

NOT NULL – This Field Can’t Be Empty

By default, SQL allows columns to store NULL (meaning: unknown or no value). But sometimes, that’s not okay.

With NOT NULL, you force the column to always have a value.

🛠️ Syntax Example


CREATE TABLE users (
    user_id INT NOT NULL,
    username VARCHAR(50) NOT NULL
);

This says: “Every user must have a user_id and a username. No blanks allowed!”

Why Use NOT NULL?

  • You require data to be present.
  • For example: You can’t have a user with no name or an order with no price.

What Happens If You Try to Skip It?


INSERT INTO users (user_id) VALUES (1);

This will fail because username is set to NOT NULL, and we didn’t provide a value for it.


UNIQUE – No Duplicates Allowed

The UNIQUE constraint ensures that every value in the column must be different. No repeats!

Syntax Example


CREATE TABLE users (
    email VARCHAR(100) UNIQUE
);

This says: “Each email must be one-of-a-kind. No two users can share the same email.”

Why Use UNIQUE?

  • Prevent duplicate records.
  • Perfect for fields like:
    • Emails
    • Usernames
    • National ID numbers

What Happens If You Try to Duplicate?


INSERT INTO users (email) VALUES ('test@example.com');
INSERT INTO users (email) VALUES ('test@example.com');

This will trigger an error: duplicate key value violates unique constraint.


Combine Them


CREATE TABLE users (
    email VARCHAR(100) NOT NULL UNIQUE
);

Now: email can never be empty and must be unique. That’s solid data integrity!


Recap

Constraint What It Does Use It When…
NOT NULL Prevents empty/missing values You require data in this column
UNIQUE Prevents duplicate values You need distinct values only

When to Use These

  • Building logins or user accounts? → Use NOT NULL and UNIQUE on email or username.
  • 🧾Invoicing system? → Use NOT NULL on amounts, dates, IDs.

Final Thoughts

SQL constraints like NOT NULL and UNIQUE help keep your database clean, accurate, and reliable. Think of them like guardrails — they stop bad data from sneaking in.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top