Ralph's Database Column Organization
TLDR:
- primary key columns (e.g.
id) - foreign key columns (e.g.
other_id) - row qualifying columns (e.g.
status) - entity identification columns (e.g.
name,title,slug,base_url) - non-string-based entity attribute columns (e.g.
rating,is_admin) - string-based entity attribute columns (e.g.
short_description,description,notes) - timestamps (e.g.
created_at,updated_at)
"Rules"
Each rule applies in order if it pertains to a necessary column in the set of columns.
-
First, Columns used as primary keys. They should be named
idunless there is a compelling reason not to (ie: it is not a surrogate key, or it is part of a composite key). -
Next, all columns used as foreign keys. These keys generally should be named <other_table>_id when there is no other contextual specification. If addition context is necessary, it shoud be prepended to the name. For example, instead of
user_idpointing to users.id, if it was a nullable relation and the contextual attribute is "primary", as good choice would beprimary_user_id. -
Next, row qualifying fields. These would be columns that qualify the row and fairly commonly used in search criteria, for example
statusmight be an enum ofActive, Inactive, oris_activea boolean/int oftrue/false. The main concept here is there is a high level peice of information that differentiates sets of rows. -
Next, columns that help identify rows in human form. Examples here include
name,first_name/last_name,title,base_url,slug, etc. -
Next, non-string based attribute columns. Examples here include
star_rating,is_admin,age,birthdate,comment_countetc. -
Next, string based attribute columns. Examples include
description,notes,content, etc. -
Finally, timestamps. Generally, these are
created_atandupdated_at
What would the ordering look like for a blog post?
id
author_id
primary_category_id
status
title
comment_count
content
created_at
updated_at
Background reading:
http://stackoverflow.com/questions/894522/is-there-any-reason-to-worry-about-the-column-order-in-a-table This deals with performance implications of column order and years of using these kind of rules have informed common practices.