Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent less than zero values in postgresql

Tags:

sql

postgresql

I am wondering in postgresql if it is possible to prevent values which are less than zero from being entered in the table.

In my example I have a stock table, which everytime an item is bought the stock is minused by one using a java application, however once it gets to zero I want it to not allow entry of values.

I know I can do this inside the java application I have made, but is it possible in postgres table itself, so when any negative numbers are entered below zero it doesn't accept the value?

I would like a method for which I can alter the table to add the constraints as I already have the table created called stock_availability and a stock_quantity column for which I want to apply the constraints of it not being less than zero to, I would prefer not to delete this table and re create it

like image 567
John Avatar asked Feb 01 '14 21:02

John


People also ask

How do I divide by 0 in PostgreSQL?

If you'd like to handle division by zero gracefully, you can use the NULLIF function. NULLIF takes two arguments: the expression of interest, and the value you want to override. If the first argument is equal to the second, then NULLIF returns NULL; otherwise, it returns the first argument.

Can Postgres numeric be negative?

In the integer data type, we can store numbers without any decimal values. You can store both positive and negative values.

What is restrict in PostgreSQL?

From postgresql documentation: RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything.

What is Smallint in Postgres?

PostgreSQL allows a type of integer type namely SMALLINT . It requires 2 bytes of storage size and can store integers in the range of -37, 767 to 32, 767. It comes in handy for storing data like the age of people, the number of pages in a book, etc. Syntax: variable_name SMALLINT.


1 Answers

Use a check constraint:

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

To add this to an existing table, use ALTER TABLE

alter table stock_availability
   add constraint stock_nonnegative check (stock_quantity >= 0);
like image 159
a_horse_with_no_name Avatar answered Oct 14 '22 22:10

a_horse_with_no_name