Video in progress
Why do we need NOT NULL and CHECK constraints, isn't it enough to do these checks in Java code?
NOT NULL guarantees a column isn't left empty, and CHECK guarantees a value follows a rule (for example price > 0), both at the database level. Validation in Java is needed, but people write to the database by other routes too (scripts, another service, hand-written SQL), and only a constraint catches those.
📖 Answer
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price numeric(12,2) NOT NULL CHECK (price > 0),
discount int NOT NULL DEFAULT 0 CHECK (discount BETWEEN 0 AND 90)
);
The @NotNull and @Positive annotations are good for giving the user a nice message. But one day someone will "quickly fix something" on prod with UPDATE products SET price = 0, or a new microservice will write without validation. With a constraint, that bad data never gets into the database.
Another benefit: a constraint also works as documentation. Looking at the schema, you know discount can't exceed 90 without reading any code.
When you add a CHECK to an existing big table, the whole table gets checked. To avoid a long lock, you can do it in two steps:
ALTER TABLE products ADD CONSTRAINT price_positive CHECK (price > 0) NOT VALID;
ALTER TABLE products VALIDATE CONSTRAINT price_positive;
Sign up to mark studied questions and save your progress.