SQL Constraints: CHECK & DEFAULT – Setting Rules and Defaults for Your Data

SQL isn’t just about storing data — it’s also about making sure that data follows the rules. That’s where CHECK and DEFAULT come in.


🔧 Quick Syntax


CREATE TABLE table_name (
    column_name datatype CHECK (condition),
    column_name datatype DEFAULT default_value
);

DEFAULT – Add a Value Automatically When None is Given

Sometimes, users forget to enter something… or maybe you just want to give them a starting value. That’s what DEFAULT is for!

Syntax Example


CREATE TABLE users (
    username VARCHAR(50),
    is_active BOOLEAN DEFAULT TRUE
);

This says: “If no value is provided for is_active, automatically use TRUE.”

Why Use DEFAULT?

  • Saves time and reduces errors
  • Ensures consistency for missing values
  • Perfect for things like:
    • created_at timestamps
    • status fields
    • Flags like is_active, is_admin, etc.

⚙️ How It Works in Practice


INSERT INTO users (username) VALUES ('maria');

The result:

usernameis_active
mariatrue

CHECK – Enforce a Rule on Column Values

CHECK is like setting a rule or filter for a column. It makes sure that only data that meets the condition gets in.

Syntax Example


CREATE TABLE products (
    name VARCHAR(100),
    price DECIMAL(10, 2) CHECK (price > 0)
);

This says: “Only allow prices that are greater than 0.”

What Happens If You Break the Rule?


INSERT INTO products (name, price) VALUES ('Mousepad', -5);

This will fail. Why? Because -5 does not pass the CHECK (price > 0) condition.

Common Uses for CHECK

  • Making sure a value falls within a range:
    • Age must be greater than 0
    • Rating between 1 and 5
  • Validating simple business rules:
    • Quantity can’t be negative
    • Salary must be above minimum wage

Recap

Constraint What It Does Use It When…
DEFAULT Inserts a value automatically when none is given You want a fallback value
CHECK Makes sure a value meets a specific condition You need to enforce a rule or range

Final Thoughts

SQL constraints like DEFAULT and CHECK help your database be smarter and safer — setting smart defaults and stopping bad data at the door. Combine them with NOT NULL, UNIQUE, and PRIMARY KEY, and you’ve got rock-solid tables.

Leave a Comment

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

Scroll to Top