Preventing less than zero values ​​in postgresql

I'm interested in postgresql if you can prevent the input of values ​​that are less than zero from the table.

In my example, I have a stock table that every time an item is bought, the stock is not used by one using the java application, but as soon as it reaches zero, I want it to not allow values ​​to be entered.

I know I can do this in a java application that I did, but is this possible in the postgres table, so when any negative numbers are entered below zero, does it not take value?

I need a method for which I can modify the table to add constraints, since I already have a table created with the name stock_availability, and a stock_quantity column for which I want to apply the restrictions of this value to at least zero, I prefer not to delete this table and don't create her

+4
source share
1 answer

Use a check constraint:

create table stock_availability
(
   stock_quantity integer not not null, 
   constraint stock_positive (check (stock_quantity >= 0))
);

To add this to an existing table, use ALTER TABLE

alter table stock_availability
   add constraint stock_positive (check (stock_quantity >= 0));
+12
source

Source: https://habr.com/ru/post/1524880/


All Articles