What are CHECK, DEFAULT, and NOT NULL constraints, and how do they help enforce data integrity?
Last updated
These are column-level constraints that keep bad data out at the database level: NOT NULL requires a value, DEFAULT supplies one when none is given, and CHECK validates that values satisfy a condition.
NOT NULL: Rejects rows where the column is missing a value: enforces that a fact is always known (e.g. every user needs an email).DEFAULT: Provides a fallback value when theINSERTomits the column (e.g.status DEFAULT 'active'orcreated_at DEFAULT CURRENT_TIMESTAMP).CHECK:Enforces a boolean rule per row (e.g.
CHECK (price >= 0)); the write fails if it evaluates to false.Note: a
CHECKpasses when the condition isNULL(unknown), so pair withNOT NULLwhen needed.
Together they push validation into the schema, so integrity holds regardless of which application or query writes the data.
[lang:sql]
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC CHECK (price >= 0),
status VARCHAR(20) DEFAULT 'active'
);
- https://www.postgresql.org/docs/current/ddl-constraints.html
- https://www.postgresql.org/docs/7.4/ddl-constraints.html
- https://learn.microsoft.com/en-us/sql/relational-databases/tables/unique-constraints-and-check-constraints?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-check-constraints?view=sql-server-ver17
- https://www.devart.com/blog/how-to-use-sql-check-constraints.html
- https://dev.to/theramoliya/sql-maintain-data-integrity-with-constraints-5h62
- https://www.youtube.com/watch?v=gsuSZposXRE
- https://medium.com/@akash-bhowad/sql-constraints-ensuring-data-integrity-in-relational-databases-2ec846f1ed1d