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

3

5

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?

Basis answered 25/2, 2009 at 7:12 Comment(0)
V
6

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

Varini answered 25/2, 2009 at 7:17 Comment(0)
B
1

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.

Basis answered 25/2, 2009 at 7:22 Comment(0)
A
1

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)
Acarology answered 25/2, 2009 at 7:48 Comment(1)
Why? What kind of differences would it make?Basis

© 2022 - 2024 — McMap. All rights reserved.