SELECT *语句中的列顺序 - 是否有保证?

15

我正在使用ORM(sqlalchemy)从PG数据库获取数据。 我想避免在手工编写的SQL语句中指定所有表列名。

到目前为止,我的假设是返回的列按照用于创建数据库表的DDL语句的顺序排列。 到目前为止,这个方法可行 - 但我想知道这是否仅仅是运气好,或者它是否在(ANSI)SQL规范中明确解释。

即ANSI SQL(因此很可能是数据库)是否保证在SELECT *语句中返回列的顺序?

我正在使用PostgreSQL 8.4作为后端数据库。

  • 是的,我知道使用ORM与手工编写的SQL语句相结合会失去ORM的优势,但无奈之举……

3
你可能有自己的理由这么做,但这是一个不好的做法。你应该明确地选择你想要使用的列。 - basgys
1个回答

20

让我们考虑SQL标准,按照此处规定的第7.9节<查询规范>:

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.

因此,换句话说,是的,SQL标准规定列应按其在T中的序号进行投影。请注意,当您的由涉及JOIN .. USING或NATURAL JOIN子句的多个表组成时,事情会变得有些棘手。然而,在选择一个简单表时,您可能可以假设顺序如预期那样。为了完整起见,表中的序号位置的含义在11.4 中进一步解释:
General Rules
     5) [...] The ordinal position included
        in the column descriptor is equal to the degree of T. [...]

接着在 11.11 <add column definition> 中(用于 ALTER TABLE 语句)

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>".

还有很多其他的SQL语句和子句依赖于在

ordinal positions

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,在标准方面非常兼容,所以如果你真的想要使用SELECT *,那就去吧!

内部的的正式规范。以下是一些例子:

我认为你是正确的。否则选择列位置(ADD COLUMN col2 ... AFTER col1)就没有意义了。 - basgys
2
@basgys:即使SQL标准实际上指定了这一点,我也永远不会依赖任何顺序(顺便说一下:Postgres不支持“ADD COLUMN ... AFTER”) - user330315

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接