I'm scripting out a fairly simple database so I can simply hand off a script to someone else for an application to use. I'm curious about where best practice/the community stand on this: When should you create your primary/foreign key constraints? Should you do it while you are creating the tables because of the continuity, or should you do it after the tables are created since it will be easier to script that way since you can create the tables in any order you wish? Are there any potential fatal flaws down the road with either pattern?
Sql-server – When do you add your foreign keys
database-designprimary-keysql server
Related Question
- Sql-server – Clustered columnstore indexes and foreign keys
- Database Design – Where to Place the Foreign Key in a One-to-One Relationship
- SQL Server – Automating Foreign Keys Update
- Sql-server – How to generate scripts to drop indexes, constraints, and keys for a database to change columns from int to bigint
- How to Truncate Tables with Dependent Foreign Key Constraints in SQL Server
- Mysql – Which one of these two contact management database designs is correct or best practice
- Sql-server – Purging of unreferenced data via unconditional DELETE, by leaning on foreign key constraints
Best Answer
I typically create the primary key constraint directly with the table:
I don't see any point in deferring that PK constraint to later (same also applies to
DEFAULT
andCHECK
constraints which I typically also define "inline" with the table creation script).However, the FK constraint, I typically define those as separate
ALTER TABLE .. ADD CONSTRAINT ...
statements, that can be run right after the table creation, or after all tables have been created - doesn't really matter: