Foreign Key naming scheme

前端 未结 10 1695
悲&欢浪女
悲&欢浪女 2020-12-12 10:55

I\'m just getting started working with foreign keys for the first time and I\'m wondering if there\'s a standard naming scheme to use for them?

Given these tables:

相关标签:
10条回答
  • 2020-12-12 11:38

    Try using upper-cased Version 4 UUID with first octet replaced by FK and '_' (underscore) instead of '-' (dash).

    E.g.

    • FK_4VPO_K4S2_A6M1_RQLEYLT1VQYV
    • FK_1786_45A6_A17C_F158C0FB343E
    • FK_45A5_4CFA_84B0_E18906927B53

    Rationale is the following

    • Strict generation algorithm => uniform names;
    • Key length is less than 30 characters, which is naming length limitation in Oracle (before 12c);
    • If your entity name changes you don't need to rename your FK like in entity-name based approach (if DB supports table rename operator);
    • One would seldom use foreign key constraint's name. E.g. DB tool usually shows what the constraint applies to. No need to be afraid of cryptic look, because you can avoid using it for "decryption".
    0 讨论(0)
  • 2020-12-12 11:39

    The standard convention in SQL Server is:

    FK_ForeignKeyTable_PrimaryKeyTable
    

    So, for example, the key between notes and tasks would be:

    FK_note_task
    

    And the key between tasks and users would be:

    FK_task_user
    

    This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:

    FK_task_user
    FK_note_task
    FK_note_user
    

    So you can see that tasks depend on users, and notes depend on both tasks and users.

    0 讨论(0)
  • 2020-12-12 11:40

    If you aren't referencing your FK's that often and using MySQL (and InnoDB) then you can just let MySQL name the FK for you.

    At a later time you can find the FK name you need by running a query.

    0 讨论(0)
  • 2020-12-12 11:43

    This is probably over-kill, but it works for me. It helps me a great deal when I am dealing with VLDBs especially. I use the following:

    CONSTRAINT [FK_ChildTableName_ChildColName_ParentTableName_PrimaryKeyColName]
    

    Of course if for some reason you are not referencing a primary key you must be referencing a column contained in a unique constraint, in this case:

    CONSTRAINT [FK_ChildTableName_ChildColumnName_ParentTableName_ColumnInUniqueConstaintName]
    

    Can it be long, yes. Has it helped keep info clear for reports, or gotten me a quick jump on that the potential issue is during a prod-alert 100% would love to know peoples thoughts on this naming convention.

    0 讨论(0)
提交回复
热议问题