Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a check constraint between two columns in SQL?

I am trying to create a Basic pay (BP) table with

CREATE TABLE bp (
   bpid       VARCHAR(5), 
      FOREIGN KEY (bpid) REFERENCES designation(desigid), 
   upperlimit DECIMAL(10,2) NOT NULL, 
   lowerlimit DECIMAL(10,2) NOT NULL, 
   increment  DECIMAL(10,2) NOT NULL 
      CONSTRAINT llvalid CHECK (upperlimit > lowerlimit)
 );

As you can see near the ending, I want to check if upperlimit is greater than lowerlimit, how can I do that?

like image 278
Unknown Avatar asked Feb 25 '09 07:02

Unknown


People also ask

How do I create a check constraint on multiple columns in SQL Server?

Use this syntax for record-level constraints: ALTER TABLE MyTable ADD CONSTRAINT MyCheck CHECK (... your check expression...)

Can two columns have one constraint?

We can create a table with more than one constraint in its columns. Following example shows how we can define different constraints on a table. Adding constraints in Create command : Sr_no is a Primary Key.


3 Answers

It might (probably does) depend on the data base you use.

Comparing to the oracle syntax (e.g. here: http://www.techonthenet.com/oracle/check.php), what you are missing might be a ',' between NULL and CONSTRAINT

like image 186
Jens Schauder Avatar answered Oct 04 '22 01:10

Jens Schauder


The problem is that you have defined it as a column level constraint but it references other columns. You must define a constraint at the table level.

ALTER TABLE bp
    ADD CONSTRAINT CK_limit CHECK ( upperlimit > lowerlimit)
like image 31
MikeW Avatar answered Oct 04 '22 03:10

MikeW


Here's proper the SQL query...

CREATE TABLE bp (bpid VARCHAR(5),
FOREIGN KEY (bpid) REFERENCES designation(desigid), 
upperlimit DECIMAL(10,2) NOT NULL,
lowerlimit DECIMAL(10,2) NOT NULL,
increment DECIMAL(10,2) NOT NULL,
CONSTRAINT llvalid CHECK (upperlimit > lowerlimit));

Note the comma after NOT NULL and CONSTRAINT in the last line.

like image 40
Unknown Avatar answered Oct 04 '22 03:10

Unknown