Naming of ID columns in database tables

后端 未结 23 675

I was wondering peoples opinions on the naming of ID columns in database tables.

If I have a table called Invoices with a primary key of an identity column I would c

相关标签:
23条回答
  • 2020-11-29 18:21

    You could use the following naming convention. It has its flaws but it solves your particular problems.

    1. Use short (3-4 characters) nicknames for the table names, i.e. Invoice - inv, InvoiceLines - invl
    2. Name the columns in the table using those nicknames, i.e. inv_id, invl_id
    3. For the reference columns use invl_inv_id for the names.

    this way you could say

    SELECT * FROM Invoice LEFT JOIN InvoiceLines ON inv_id = invl_inv_id
    
    0 讨论(0)
  • 2020-11-29 18:27

    For each table I choose a tree letter shorthand(e.g. Employees => Emp)

    That way a numeric autonumber primary key becomes nkEmp.

    It is short, unique in the entire database and I know exactly its properties at a glance.

    I keep the same names in SQL and all languages I use (mostly C#, Javascript, VB6).

    0 讨论(0)
  • 2020-11-29 18:28

    I think you can use anything for the "ID" as long as you're consistent. Including the table name is important to. I would suggest using a modeling tool like Erwin to enforce the naming conventions and standards so when writing queries it's easy to understand the relationships that may exist between tables.

    What I mean by the first statement is, instead of ID you can use something else like 'recno'. So then this table would have a PK of invoice_recno and so on.

    Cheers, Ben

    0 讨论(0)
  • 2020-11-29 18:28

    I definitely agree with including the table name in the ID field name, for exactly the reasons you give. Generally, this is the only field where I would include the table name.

    0 讨论(0)
  • 2020-11-29 18:29

    If you give each key a unique name, e.g. "invoices.invoice_id" instead of "invoices.id", then you can use the "natural join" and "using" operators with no worries. E.g.

    SELECT * FROM invoices NATURAL JOIN invoice_lines
    SELECT * FROM invoices JOIN invoice_lines USING (invoice_id)
    

    instead of

    SELECT * from invoices JOIN invoice_lines
        ON invoices.id = invoice_lines.invoice_id
    

    SQL is verbose enough without making it more verbose.

    0 讨论(0)
提交回复
热议问题