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

时间:2012-07-31 09:40:19

标签: sql postgresql sqlalchemy ansi-sql

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

到目前为止,我的假设是返回的列按照用于创建db表的DDL语句的顺序排列。到目前为止,这是有效的 - 但我想知道这只是运气,还是在(ANSI)SQL规范中专门解决。

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

我使用PostgreSQL 8.4作为我的后端db

  • 是的,我知道在ORM中使用手工制作的SQL语句会破坏ORM的目的,但需要......

1 个答案:

答案 0 :(得分:13)

让我们考虑SQL标准,此处指定的7.9 <query specification>部分:

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中的序数位置来投影列。请注意,当<table expression>包含多个涉及JOIN .. USINGNATURAL JOIN子句的表时,事情会变得有点棘手。但是,从简单的表中进行选择时,假设订单符合预期,您可能会很好。

为了完整起见,ordinal position within T进一步解释了11.4 <column definition>表的含义:

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<table expressions>的正式规范。一些例子:

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 *,请继续!