Is there any use to duplicate column names in a table?

后端 未结 3 1742
太阳男子
太阳男子 2021-01-23 02:24

In sqlite3, I can force two columns to alias to the same name, as in the following query:

SELECT field_one AS overloaded_name,
       field_two AS overloaded_nam         


        
3条回答
  •  日久生厌
    2021-01-23 03:01

    I assume you're talking about the CREATE TABLE ... AS SELECT command. This looks like an SQL extension to me.

    Standard SQL does not allow you to use the same column name for different columns, and SQLite appears to be allowing that in its extension, but working around it. While a simple, naked select statement simply uses as to set the column name, create table ... as select uses it to create a brand new table with those column names.

    As an aside, it would be interesting to see what the naked select does when you try to use the duplicated column, such as in an order by clause.

    If you were allowed to have multiple columns with the same name, it would be a little difficult for the execution engine to figure out what you meant with:

    select overloaded_name from table;
    

    The reason why you can do it in the select is to allow things like:

    select id, surname   as name from users where surname is not null
    union all
    select id, firstname as name from users where surname is     null
    

    so that you end up with a single name column.

    As to whether there's a good reason, SQLite is probably assuming you know what you're doing when you specify the same column name for two different columns. Its essence seems to be to allow a great deal of latitude to the user (as evidenced by the fact that the columns are dynamically typed, for example).

    The alternative would be to simply refuse your request, which is what I'd prefer, but the developers of SQLite are probably more liberal (or less anal-retentive) than I :-)

提交回复
热议问题