How can I write a condition in a create table statement to say 2 columns cannot be equal?
CREATE table Example(
sendId integer,
recieveId integer,
**!sendId cannot equal recieveId**
);
How can I write a condition in a create table statement to say 2 columns cannot be equal?
CREATE table Example(
sendId integer,
recieveId integer,
**!sendId cannot equal recieveId**
);
Use a check constraint:
CREATE table Example(
sendId integer,
recieveId integer,
constraint not_equal check (sendid <> recieveId)
);
As your columns allow null values, you might want to take care of that too:
CREATE table Example(
sendId integer,
recieveId integer,
constraint not_equal check (coalesce(sendid,0) <> coalesce(recieveId,0))
);
That treats NULL
as 0
maybe using a different value that could never occur might be more appropriate.
Depending on your DBMS product, you could also use the standard operator is distinct from
constraint not_equal check (sendid is distinct from receiveid)
You would use a check
constraint:
create table Example (
sendId integer,
receiveId integer,
constraint chk_example_sendId_receiveId check (sendId <> receiveId)
);
You need check
constraint :
constraint chk_sendId_receiveId check (sendId <> receiveId)