Sobes.tech
Junior — Middle

Is it possible to set a constraint on a database column to allow only non-null values?

sobes.tech AI

Answer from AI

Yes, in a database, you can set a constraint on a column to allow only non-zero values. This is done using a CHECK constraint that verifies the column's value is not zero.

Example for SQL:

ALTER TABLE table_name
ADD CONSTRAINT check_column_nonzero CHECK (column_name <> 0);

This constraint will prevent inserting or updating a record with a zero value in the specified column.

If using JPA/Hibernate, you can add the @Column(nullable = false) annotation to disallow NULL, but to specifically disallow zero, you need to use custom checks or database-level constraints, as shown above.