Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database column naming for foreign key

should I signal the foreign key in a database column name?

FKOrder vs. FK_Order vs. Order

like image 766
dieter Avatar asked Apr 13 '11 10:04

dieter


People also ask

Can foreign key column name be different?

A foreign key can also have different column names than the primary key. The foreign key and primary key can also have different default values. However, since values in the referenced table must be unique, default values are not much used and are rarely used for columns that are part of a primary key.

How do you name columns in database?

Database object names, particularly column names, should be a noun describing the field or object. Avoid using words that are just data types such as text or timestamp . The latter is particularly bad as it provides zero context. Underscores separate words.

Should foreign keys have the same name?

Though it's not required that name of a foreign key must be the same with primary key, we have kept it the same as per standard SQL best practices.


1 Answers

The short answer is no - don't put "FK" in column names of foreign key columns. You can still signal the intent of the column though, here's how I do it:

Naming foreign key columns

It depends on your naming convention for the target of the FK. If you have Id, then I'd prepend the table name when creating FK columns.

Example 1:
For table User with PK Id and table Workitem with user ID FK, I'd call the column Workitem.UserId.

If there were more than one FK between the same tables, I'd make this clear in the column name:

Example 2:
For table User with PK Id and table Workitem with "assigned to user ID" and "created by user ID" FKs, I'd call the columns Workitem.CreatedByUserId and Workitem.AssignedToUserId.

If your naming convention for PKs is more like UserId, then you'd factor that into the above examples so as not to end up with UserUserId.

Naming foreign key constraints

This is mine:

FK_childtablename_[differentiator]parenttablename

The differentiator is used when there is more than one FK between the same two tables (e.g. CreatedByUserId and AssignedToUserId). Often I use the child table's column name for this.

Example 1:
Given tables: Workitem and User Where User has CreatedByUserId and AssignedToUserId Foreign key names are FK_Workitem_User_CreatedByUser and FK_Workitem_AssignedToUser

I use double-underscores if tables/columns have underscores in the name:

Example 2:
Given tables: work_item and user Where user has created_by_user_id and assigned_to_user_id Foreign key names are FK_work_item__created_by_user and FK_work_item__assigned_to_user

like image 100
Neil Barnwell Avatar answered Oct 01 '22 19:10

Neil Barnwell