Search code examples
sqlnaming-conventions

Naming of ID columns in database tables


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 call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.

Where I am workind current they have called all ID columns ID.

So they would do the following:

Select  
    i.ID 
,   il.ID 
From
    Invoices i
    Left Join InvoiceLines il
        on i.ID = il.InvoiceID

Now, I see a few problems here:
1. You would need to alias the columns on the select
2. ID = InvoiceID does not fit in my brain
3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on?

What are other peoples thoughts on the topic?


Solution

  • ID is a SQL Antipattern. See http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&field-keywords=sql+antipatterns&sprefix=sql+a

    If you have many tables with ID as the id, you are making reporting that much more difficult. It obscures meaning and makes complex queries harder to read as well as requiring you to use aliases to differentiate on the report itself.

    Further, if someone is foolish enough to use a natural join in a database where they are available, you will join to the wrong records.

    If you would like to use the USING syntax that some dbs allow, you cannot if you use ID.

    If you use ID, you can easily end up with a mistaken join if you happen to be copying the join syntax (don't tell me that no one ever does this!) and forget to change the alias in the join condition.

    So you now have

    select t1.field1, t2.field2, t3.field3
    from table1 t1 
    join table2 t2 on t1.id = t2.table1id
    join table3 t3 on t1.id = t3.table2id
    

    when you meant

    select t1.field1, t2.field2, t3.field3 
    from table1 t1 
    join table2 t2 on t1.id = t2.table1id
    join table3 t3 on t2.id = t3.table2id
    

    If you use tablenameID as the id field, this kind of accidental mistake is far less likely to happen and much easier to find.