Although, it could look like primary opinion based question, it is not absolutely the case.
I wonder what are pros and cons for each of possible conventions of creating constraints in SQL. Since I use SQL Server, I will show three examples of creating primary key constraints, that I'm familiared with:
CREATE TABLE Persons (Id int NOT NULL PRIMARY KEY);
CREATE TABLE Persons (Id int NOT NULL, CONSTRAINT PK_Persons_Id PRIMARY KEY(Id));
CREATE TABLE Persons (Id int NOT NULL); ALTER TABLE Persons ADD CONSTRAINT PK_Persons_Id PRIMARY KEY (Id);
Those are pros and cons, that I've discovered so far. Maybe more experienced developer can point out other factors that could help to make best decision while creating a primary key and other constraints in development and production environments. E.g.:
I believe that we could share our knowledge about when one syntax had actual benefits over other.
From an operational point of view: Give every constraint its own unique name, so you can change or remove the constraint later by referencing it by its name.
Additionally I prefer and normal index plus a named unique constraint to an unique index, so I can remove the constraint later without losing the index, when the DBMS supports this. Actually I have only seen this on Oracle: There you can back a unique constraint with an ordinary (non-unique) index. When dropping the constraint, the index stays. This can be very important for stable execution plans ("plan stability"). Unfortunately it looks like neither SQL Server nor PostgreSQL support this feature in their current versions.
With separately named constraints it is also easier to diff database schemas: You just enumerate all table names, column names, index names and constraint names sorted by name into a flat file. You can then easily compare this with a reference file and look for unexpected differences. This is much harder, when you don't have stable names and have to compare the semantics of the constraints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With