1

Considering this table > TRIP Table : ( Code [pk] , Origin , Destination , Distance ) how to make (Origin , Destination) attributes has the constraint of composite key "can repeat if one of them is different" .

1
  • 1
    Hi there, welcome to the site, What RDBMS are you using?
    – Tom V
    Commented Dec 7, 2016 at 21:21

1 Answer 1

0

Not sure where there complexity is. Use a UNIQUE constraint on a composite key.

CREATE TABLE foo (
  a int,
  b int,
  UNIQUE(a,b)
);
INSERT INTO foo VALUES (1, null), (2, null);
INSERT INTO foo VALUES (null,1), (null,2);

But,

INSERT INTO foo VALUES (2,2), (2,2);
ERROR:  duplicate key value violates unique constraint "foo_a_b_key"
DETAIL:  Key (a, b)=(2, 2) already exists.

If you're not creating the table but modifying one already made, you can use this:

ALTER TABLE foo ADD CONSTRAINT foobar UNIQUE (a, b);
2
  • 1
    Doesn't it depend on the RDBMS used? for example: ORA-00911: invalid character
    – Tom V
    Commented Dec 7, 2016 at 21:25
  • Oracle does the same thing, but I'm not sure it provides for the unique constraint in the table. May have to use ALTER TABLE t ADD CONSTRAINT u_t UNIQUE (id1, id2); Commented Dec 7, 2016 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.