Should I Always Fully Qualify Column Names In SQL?

后端 未结 11 1169
小鲜肉
小鲜肉 2021-02-14 02:48

Out of interest when working with SQL statements should I always use the fully qualifed column name (tablename.columnname) even if only working with one table e.g.



        
11条回答
  •  名媛妹妹
    2021-02-14 03:45

    I generally follow these rules:

    When using a single table, it is not necessary to use the table name prefix:

    SELECT col1, col2 FROM table1
    

    For multiple tables, use the full table name. Aliases can be confusing, especially when doing multiple joins:

    SELECT table1.col1, table2.col2 FROM table1 INNER JOIN table2 on 
                table1.id = table2.id
    

    I see many developers using table aliases, but particularly in large projects with multiple developers, these can become cryptic. A few extra keystrokes can provide a lot more clarity in the code.

    If may, however, become necessary to use a column alias when columns have the same name. In that case:

        SELECT table1.col1, table2.col1 as table2_col1 FROM table1 
                INNER JOIN table2 on 
                table1.id = table2.id
    

提交回复
热议问题