Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming the MYSQL id column

Tags:

mysql

What is the best practice for naming the column that is the primary key for a mysql table? I have seen two ways:

  1. 'id'
  2. tableName_id (Where tableName is substituted for the name of the table).

I would have thought just id would suffice, because you can still uniquely identify the column by selecting the column proceeded by a period and the table name (i.e. for the column 'id' in the table 'cars', you could select it as cars.id)

Or am I over-thinking it all?

like image 455
Globalz Avatar asked Nov 01 '10 11:11

Globalz


People also ask

How do you name ID columns?

For columns that are the primary key for a table and uniquely identify each record in the table, the name should be [TableName] + “Id” (e.g. On the Make table, the primary key column would be “MakeId”).

How do you name a column in MySQL?

To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.

Why is ID a primary key?

In the relational model of databases, a primary key is a specific choice of a minimal set of attributes (columns) that uniquely specify a tuple (row) in a relation (table). Informally, a primary key is "which attributes identify a record," and in simple cases constitute a single attribute: a unique ID.

Does MySQL have ID?

@T.J. Crowder: MySQL doesn't have row id's outside whatever is in the table like eg. Postres does. The only unique identifier in a MySQL table is any unique index/primary key in the table.


1 Answers

I usually name them as [tblname]_id. The reason is simple. Let's say I have two tables:

member
    member_id
    member_alias
    ...

post
    post_id
    member_id
    post_text
    ...

Now I can join them with MySQLs USING-syntax and save a few characters for each join:

SELECT post.*, member_id, member_alias FROM post
    INNER JOIN member USING (member_id)

Of course, this is all mostly subjective.

like image 124
Emil H Avatar answered Oct 13 '22 14:10

Emil H