In this lesson, you will learn how to protect your database from "garbage data" by defining strict rules for what information is allowed to live in your columns.
The Importance of Data Validity
Imagine you are building a database for a library. You have an attribute for the publication_year of a book. Without any rules, a user could accidentally type "banana" or the year "3000" into that column. In the world of databases, we use Domain Constraints to prevent this.
A domain constraint is a rule that defines the "permissible set of values" for a specific attribute. By setting these rules, you act as a gatekeeper: the database will reject any input that doesn’t fit the criteria, ensuring that every piece of data remains meaningful and acceptable.
Seeing it in Action
When we define a table, we don't just give a column a name; we give it a Domain. Think of this as defining the "DNA" of that column.
For example, consider a Members table:
CREATE TABLE Members (
member_id INT,
age INT CHECK (age >= 18),
membership_status CHAR(1) CHECK (membership_status IN ('A', 'I'))
);
In this example, the domain constraints act as our safety net:
CHECK (age >= 18): This ensures that no one under 18 can be entered into the system. If someone tries to enter age 15, the database rejects it.CHECK (membership_status IN ('A', 'I')): This restricts the input to only two meaningful options—'A' for Active or 'I' for Inactive. Any other character, like 'X' or 'Z', is blocked.
Why does this matter?
If your database allows invalid data, your reports, calculations, and future queries will produce incorrect results. By establishing domain constraints at the very beginning, you ensure the integrity of your data. It is much easier to prevent a mistake at the moment of entry than it is to clean up a database full of messy, nonsensical information later.
Key Takeaway: Domain constraints define the allowed range and format of data for an attribute, acting as a mandatory filter that ensures only valid, meaningful information is stored in your database.