Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure about non negative column?

I need to create a table Branch with columns branch_name and branch_city character type, assets as integer type. branch_name is the primary key and I have to ensure that assets are non negative.

I tried like

CREATE TABLE Branch
(
    branch_name navarchar(100) primary key,
    branch_city nvarchar(100),
    assests int NOT NULL
)
like image 560
Neo Avatar asked Jul 16 '12 05:07

Neo


People also ask

How do you avoid negative values in SQL?

First, change your query: Then, instead of using ExecuteNonQuery use ExecuteScalar and check if the number of records modified is 0 it means that the @quantity is bigger than the value of qty . Also, I would recommend adding a check constraint as shown in Larnu's answer.

Can we insert negative values in identity column?

However, it is possible to change,you can specify negative seeds and increments for identity columns,so you can reset the identity column of the sysdatabases table to -1, -1 and the next database you create will have ID -1, then -2, etc.

Can INT take negative values in SQL?

Well all integer datatypes in SQL (except for tinyint) are signed datatypes, that's what lets us represent both positive and negative numbers. Because a value can be either positive or negative we need some way to tell them apart. In binary, if we want to represent a negative number we use the twos' complement value.

Which operator can be used to negative values in a column in SQL?

The + (Positive) and - (Negative) operators can be used on any expression of any one of the data types of the numeric data type category.


2 Answers

You need to define a datatype for your primary key, and you need to add a CHECK constraint to ensure assets is non-negative:

CREATE TABLE dbo.Branch
(
    branch_name NVARCHAR(100) primary key,
    branch_city nvarchar(100),
    assets int NOT NULL CHECK (assets >= 0)
)
like image 58
marc_s Avatar answered Sep 25 '22 18:09

marc_s


Alter your table creating a constraint to check the column

ALTER TABLE Branch ADD CONSTRAINT chkassets CHECK (assets > 0);
like image 40
Krunal Mevada Avatar answered Sep 22 '22 18:09

Krunal Mevada