Inline vs. Out-of-line Constraints?
Today one of my more feisty colleages and I had a discussion about constraints. I had asked him if he wouldn’t mind naming the NOT NULL constraints to a particular table definition. With this guy, nothing is easy. ;-)
So he came over and we talked about inline vs. out-of-line constraints. I asked him the advantage of out-of-line. He asked me the advantage of inline. I’m sure his answer was better than mine as he is much more articulate.
For me, it’s mostly a style thing, except for FOREIGN KEY constraints which, if defined inline, will inherit the data type of the parent column. That makes life easier if you ever need to change the data type of a parent key (not a recommended best practice mind you). I just think it looks prettier (factual based evidence). It’s all in one file and I like to see how many constraints I can put on a single table. I’m shooting for at least one per column to save myself time down the road of coding exceptions. Let the database do it’s job!
Here’s a sample of inline constraints:
DROP TABLE s;
DROP TABLE t;
CREATE TABLE t
(
id NUMBER(10)
CONSTRAINT pk_id PRIMARY KEY,
name VARCHAR2(30)
CONSTRAINT nn_name_t NOT NULL,
age NUMBER(2,0)
CONSTRAINT nn_age_t NOT NULL
CONSTRAINT ck_gtzero_age_t CHECK ( age >= 0 )
);
CREATE TABLE s
(
sid NUMBER(10)
CONSTRAINT pk_sid PRIMARY KEY,
id
CONSTRAINT fk_id_s REFERENCES t ( id ),
something_unique VARCHAR2(30)
CONSTRAINT uq_somethingunique_s UNIQUE
);
And out-of-line Constraints:
DROP TABLE s;
DROP TABLE t;
CREATE TABLE t
(
id NUMBER(10),
name VARCHAR2(30),
age NUMBER(2,0)
);
ALTER TABLE t ADD CONSTRAINT pk_id PRIMARY KEY ( id );
ALTER TABLE t ADD CONSTRAINT nn_name_t CHECK ( name IS NOT NULL );
ALTER TABLE t ADD CONSTRAINT nn_age_t CHECK ( age IS NOT NULL );
ALTER TABLE t ADD CONSTRAINT ck_gtzero_age_t CHECK ( age >= 0 );
CREATE TABLE s
(
sid NUMBER(10),
id NUMBER(10),
something_unique VARCHAR2(30)
);
ALTER TABLE s ADD CONSTRAINT pk_sid PRIMARY KEY ( sid );
ALTER TABLE s
ADD CONSTRAINT fk_id_s FOREIGN KEY ( id ) REFERENCES t ( id );
ALTER TABLE s
ADD CONSTRAINT uq_somethingunique_s UNIQUE ( something_unique );
So, what are the advantages for either method? I couldn’t find much via google or asktom, but I probably just didn’t search on the right terms. I find it hard to believe that this topic hasn’t come up before.
* Note that I did use
5 constraint typesLabels: constraints, database