Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The values of one column cannot be greater than another

I am trying to create a table where the values in one column can't be greater than the next column over. For example, I am creating the following table.

CREATE TABLE Price (
    PriceID INT PRIMARY KEY IDENTITY (1,1),
    OriginalPrice FLOAT NOT NULL,
    CurrentPrice FLOAT NOT NULL,
    Discount FLOAT,
    ShippingCost FLOAT NOT NULL,
    Tax FLOAT NOT NULL);

And Current Price cannot be greater than OriginalPrice.

So what I tried doing was

CurrentPrice FLOAT CHECK (CurrentPrice <= OriginalPrice) NOT NULL,

But this gives me the following error:

Msg 8141, Level 16, State 0, Line 1
Column CHECK constraint for column 'CurrentPrice' references another column, table 'Price'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

Am I not allowed to reference a column in the same table?

like image 251
krikara Avatar asked Nov 15 '12 01:11

krikara


People also ask

Is there a limit to columns in SQL?

In SQL Server you can include non-key columns in a nonclustered index, to avoid the limitation of a maximum of 32 key columns. For more information, see Create Indexes with Included Columns. Tables that include sparse column sets include up to 30,000 columns.

Can we have more than one column defined to be unique?

You can create UNIQUE constraints using CREATE TABLE or ALTER TABLE statement. You can create a UNIQUE constraint on one or more columns of a table.

How do I change the value of a specific column?

We have to use the SET keyword in the UPDATE command for modifying the value of the columns. WHERE clause specifies which row you want to change.

How can we check constraints on a table using query in SQL Server?

Use the view table_constraints in the information_schema schema. The column table_name gives you the name of the table in which the constraint is defined, and the column constraint_name contains the name of the constraint.


1 Answers

Just change it to a table-level constraint instead of a column constraint.

CREATE TABLE Price (
    PriceID INT PRIMARY KEY IDENTITY (1,1),
    OriginalPrice FLOAT NOT NULL,
    CurrentPrice FLOAT NOT NULL,
    Discount FLOAT,
    ShippingCost FLOAT NOT NULL,
    Tax FLOAT NOT NULL,
    CHECK (CurrentPrice <= OriginalPrice));

You can also add it after, e.g.

ALTER TABLE Price ADD CHECK (CurrentPrice <= OriginalPrice);
--or
ALTER TABLE Price ADD CONSTRAINT CK_Price_Current_vs_Original
    CHECK (CurrentPrice <= OriginalPrice);
like image 173
RichardTheKiwi Avatar answered Sep 30 '22 13:09

RichardTheKiwi