column order in SELECT * statement - guaranteed?

馋奶兔 提交于 2019-12-05 05:29:23

Let's consider the SQL standard, section 7.9 <query specification> as specified here:

http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

<query specification> ::=
          SELECT [ <set quantifier> ] <select list> <table expression>
[...]
<select list> ::=
            <asterisk>
          | <select sublist> [ { <comma> <select sublist> }... ]

[...]
Syntax Rules
1) Let T be the result of the <table expression>.
3) Case:
       a) [...]
       b) Otherwise, the <select list> "*" is equivalent to a <value
          expression> sequence in which each <value expression> is a
          <column reference> that references a column of T and each
          column of T is referenced exactly once. The columns are ref-
          erenced in the ascending sequence of their ordinal position
          within T.

So, in other words, yes, the SQL standard specifies that columns are to be projected according to their ordinal position within T. Note, that things get a bit tricky, when your <table expression> consists of several tables involving JOIN .. USING or NATURAL JOIN clauses. However, when selecting from a simple table, you're probably fine assuming that the order is as expected.

For completeness, the meaning of an ordinal position within T for tables is explained further down in 11.4 <column definition>:

General Rules
     5) [...] The ordinal position included
        in the column descriptor is equal to the degree of T. [...]

And then in 11.11 <add column definition> (for ALTER TABLE statements)

General Rules
     4) [...] In particular, the degree of T
        is increased by 1 and the ordinal position of that column is
        equal to the new degree of T as specified in the General Rules
        of Subclause 11.4, "<column definition>".

There are quite a few other SQL statements and clauses that depend on the formal specification of ordinal positions within <table expressions>. Some examples:

13.8 <insert statement> 
     (when omitting the `<insert column list>`)
20.2 <direct select statement: multiple rows>
     (when `<sort specification>` contains an `<unsigned integer>`)

Postgres, in particular, is quite standards-compliant, so if you really want to SELECT *, go ahead!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!