Sql naming best practice

前端 未结 12 2779
春和景丽
春和景丽 2021-02-14 09:48

I\'m not entirely sure if there\'s a standard in the industry or otherwise, so I\'m asking here.

I\'m naming a Users table, and I\'m not entire

12条回答
  •  南旧
    南旧 (楼主)
    2021-02-14 10:26

    First of all, I would suggest using the singular noun, i.e. user instead of users, although this is more of a personal preference.

    Second, there are some who prefer to always name the primary key column id, instead of user_id (i.e. table name + id), and similar with for example name instead of employee_name. I think this is a bad idea for the following reason:

    -- when every table has an "id" (or "name") column, you get duplicate column names in the output:
    select e.id, e.name, d.id, d.name
    from employee e, department d
    where e.department_id = d.id
    
    -- to avoid this, you need to specify column aliases every time you query:
    select e.id employee_id, e.name employee_name, d.id department_id, d.name department_name
    from employee e, department d
    where e.department_id = d.id
    
    -- if the column name includes the table, there are no conflicts, and the join condition is very clear
    select e.employee_id, e.employee_name, d.department_id, d.department_name
    from employee e, department d
    where e.department_id = d.department_id
    

    I'm not saying you should include the table name in every column in the table, but do it for the key (id) column and other "generic" columns such as name, description, remarks, etc. that are likely to be included in queries.

提交回复
热议问题