Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - naming of ID columns

I've always wondered what are the pros and the cons of these ID naming styles in SQL:

CREATE TABLE cache (
id INT AUTO_INCREMENT,
PRIMARY KEY(id)
);

CREATE TABLE cache (
cid INT AUTO_INCREMENT,
PRIMARY KEY(id)
);

CREATE TABLE cache (
cache_id INT AUTO_INCREMENT,
PRIMARY KEY(id)
);

Why some developers use "id" in each table, some prefix it with one letter of the table name or with the entire table name along with one underscore?

like image 531
Tower Avatar asked Nov 29 '22 11:11

Tower


2 Answers

It's all a personal preference. I personally use Id simply because I think of each table as its own entity...then when I reference with a key it becomes CustomerId or OrderId depending on the name of the table.

like image 26
Justin Niessner Avatar answered Dec 01 '22 03:12

Justin Niessner


Subjective, but I like to use named ids (e.g. customer_id, item_id, etc.)

My reasoning is that if you name your foreign keys consistently it makes joins easier to understand - it's always a.customer_id = b.customer_id. Otherwise, with complicated queries that use lots of joins, you have a sea of "id" columns and it's not immediately obvious what goes with what.

ETA:

Also, if you are using MySQL, you can use the simpler join syntax, e.g.:

FROM customers INNER JOIN orders USING customer_id
like image 178
Eric Petroelje Avatar answered Dec 01 '22 01:12

Eric Petroelje