Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for column naming in Sql [closed]

Tags:

Say I have a table called Student. Which of the following naming conventions do you prefer for the columns? You can also suggest your own.

Student
-------
StudentID
StudentName
MentorID

Student
-------
StudentID
Name
MentorID

Student
-------
ID
Name
MentorID
like image 904
Shawn Avatar asked Mar 19 '09 20:03

Shawn


3 Answers

I would go with the second one.

Student ------- StudentID Name MentorID 

I like have the name of the table in the Primary key, but it doesn't need to be on every field. Also MentorID would be how I'd name a foreign key as well (assuming Mentor is the name of the table it's pointing to).

This way the MentorID field in the Student table has the same name as the MentorID field in the Mentor table. Some people don't like it because it can be a bit confusing when joining tables, but I prefer to explicitly name the tables of the fields in joins anyway,

like image 120
Ray Avatar answered Oct 07 '22 01:10

Ray


Since regular RDBMS are kind of hierarchical, a DBMS contains a database - a database contains a table - a table contains a column - a column contains a value, I don't like the iterative use of table names in the column names.

My vote goes to:

Student -------- id (pk) name mentor (fk) (alt. mentorId) 

It's fairly easy to select correct fields, and in case of joins between tables I often rename the column names, i.e:

SELECT s.id AS StudentID, s.name AS StudentName, m.id AS MentorId, m.name AS MentorName FROM Studens AS s INNER JOIN Mentors AS m ON m.id=s.mentor 
like image 38
Björn Avatar answered Oct 07 '22 01:10

Björn


since some sql formatters uppercase stuff, i go with the follwing:

student
-------
id
name
mentor_id

that way i can keep word separation in the db.

in OO-code i use the corresponding camel-case names

mentorId, getMentorId()

like image 34
Andreas Petersson Avatar answered Oct 07 '22 01:10

Andreas Petersson