0
0
SQLquery~3 mins

Why CHECK constraint in SQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your database could catch mistakes before they happen, saving you hours of fixing errors?

The Scenario

Imagine you are managing a guest list for a party using a simple spreadsheet. You want to make sure that the age of each guest is always 18 or older, but you have to check every entry manually to catch mistakes.

The Problem

Manually checking each age is slow and easy to forget. Mistakes slip through, like entering 15 or 120 by accident. This causes confusion and errors later when you try to use the data.

The Solution

The CHECK constraint in a database automatically ensures that data meets rules like "age must be 18 or older". It stops wrong data from being saved, so you never have to hunt for errors later.

Before vs After
Before
INSERT INTO guests (name, age) VALUES ('Alice', 15); -- No check, wrong data allowed
After
CREATE TABLE guests (name VARCHAR(50), age INT CHECK (age >= 18));
What It Enables

It lets you trust your data is correct and consistent without extra work.

Real Life Example

In a hospital database, a CHECK constraint can ensure patient ages are realistic, preventing impossible values like negative numbers or ages over 150.

Key Takeaways

CHECK constraints automatically enforce rules on data.

They prevent invalid data from entering the database.

This saves time and avoids errors in data management.