8๏ธโƒฃ ๐Ÿ›‘ MySQL Constraints & Keys
Estimated reading: 3 minutes 37 views

๐Ÿšซ MySQL Constraints Overview โ€“ NOT NULL, DEFAULT, CHECK


๐Ÿงฒ Introduction โ€“ Why Use Constraints?

MySQL constraints are rules enforced at the database level to ensure data quality, validity, and reliability. Constraints like NOT NULL, DEFAULT, and CHECK help prevent:

  • Missing or invalid values
  • Inconsistent data entries
  • Incorrect logic in your applications

By defining constraints in your schema, you offload responsibility from application logic and ensure database-level integrity.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to use NOT NULL, DEFAULT, and CHECK constraints
  • Their syntax and behavior in MySQL 8+
  • Practical examples and best practices

โ— 1. NOT NULL โ€“ Disallow Missing Values

๐Ÿ”น Syntax

column_name data_type NOT NULL

๐Ÿ”น Example

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL,
  email VARCHAR(100)
);

Explanation:

  • username is required โ€” attempts to insert NULL will fail.
  • Enforces presence of critical values like names, passwords, etc.

๐Ÿ’ก 2. DEFAULT โ€“ Provide a Fallback Value

๐Ÿ”น Syntax

column_name data_type DEFAULT default_value

๐Ÿ”น Example

CREATE TABLE tasks (
  task_id INT PRIMARY KEY,
  status VARCHAR(20) DEFAULT 'pending',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Explanation:

  • status: Defaults to 'pending' if not specified.
  • created_at: Automatically records insert time.

โœ… Useful for audit columns, flags, and optional fields.


โœ… 3. CHECK โ€“ Validate Conditions (MySQL 8+)

๐Ÿ”น Syntax

CHECK (expression)

๐Ÿ”น Column-Level Example

CREATE TABLE products (
  id INT PRIMARY KEY,
  price DECIMAL(10,2) CHECK (price >= 0)
);

Explanation:

  • Ensures price is not negative.
  • Inserts or updates violating the condition will fail.

๐Ÿ”น Table-Level Example

CREATE TABLE accounts (
  id INT,
  balance DECIMAL(10,2),
  CHECK (balance <= 100000)
);

Note:
MySQL 5.x parses but ignores CHECK. Enforced only from MySQL 8.0.16+.


๐Ÿ“‹ Constraint Comparison Table

ConstraintPurposeEnforced InExample Use Case
NOT NULLDisallow missing valuesAll MySQL versionsRequired fields (username)
DEFAULTProvide fallback valueAll MySQL versionsStatus flags, timestamps
CHECKEnforce conditional rulesMySQL 8.0.16+Salary โ‰ฅ 0, Age โ‰ค 120

๐Ÿงช Add Constraints to Existing Tables

๐Ÿ”น Add NOT NULL

ALTER TABLE users MODIFY email VARCHAR(100) NOT NULL;

๐Ÿ”น Add DEFAULT

ALTER TABLE tasks ALTER COLUMN status SET DEFAULT 'pending';

๐Ÿ”น Add CHECK

ALTER TABLE products ADD CHECK (stock >= 0);

โŒ Constraint Violations โ€“ When Do Errors Occur?

ConstraintViolation ExampleResult
NOT NULLInsert with NULL usernameError
DEFAULTNone provided (uses default)No error
CHECKInsert with price = -10Error (if CHECK enforced)

๐Ÿ“˜ Best Practices

โœ… Tip๐Ÿ’ก Why It Matters
Always use NOT NULL for required fieldsAvoids null reference issues in app logic
Set DEFAULT for non-critical fieldsSimplifies insert queries
Use CHECK for critical logic conditionsKeeps logic centralized in schema
Validate CHECK support in versionAvoid silent failures in old MySQL versions
Name constraints explicitly (optional)Easier to reference when dropping or altering

๐Ÿš€ Real-World Use Cases

Use CaseConstraintWhy
Ensure status is always setDEFAULTDefaults to 'pending'
Prevent negative inventoryCHECKstock >= 0 condition
Force email entryNOT NULLAvoids incomplete user records
Audit timestampsDEFAULT TIMESTAMPAutomates logging without manual input

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Constraints like NOT NULL, DEFAULT, and CHECK help you design smart, self-validating schemas. They ensure required fields exist, fallbacks are applied, and invalid data is rejected at the source.

๐Ÿ” Key Takeaways

  • Use NOT NULL to enforce required fields
  • Use DEFAULT to simplify inserts and set fallback logic
  • Use CHECK to define conditional business rules
  • CHECK is enforced only in MySQL 8.0.16+

โš™๏ธ Real-World Relevance

These constraints are essential for CRM, billing, e-commerce, ERP, HR systems, and more where data rules must be enforced automatically.


โ“ FAQ โ€“ MySQL Constraint Overview


โ“ Is CHECK enforced in all MySQL versions?

โŒ No. Itโ€™s only enforced in MySQL 8.0.16+.


โ“ Can I have both DEFAULT and NOT NULL?

โœ… Yes, and it’s recommended:

status VARCHAR(20) NOT NULL DEFAULT 'active'

โ“ What happens if I insert nothing into a DEFAULT column?

The default value will be used automatically.


โ“ Can I remove a CHECK constraint?

โœ… Yes:

ALTER TABLE table_name DROP CHECK check_name;

Youโ€™ll need the constraint name.


โ“ Can I use expressions in DEFAULT?

โœ… Yes (e.g., CURRENT_TIMESTAMP),
โŒ But not complex expressions like functions or subqueries.


Share Now :

Leave a Reply

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

Share

๐Ÿšซ MySQL Constraints Overview (NOT NULL, DEFAULT, CHECK)

Or Copy Link

CONTENTS
Scroll to Top