列顺序在SELECT *语句 - 保证?(column order in SELECT * stat

2019-07-30 16:38发布

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

我的假设到目前为止返回的列是用于创建数据库表的DDL语句的顺序。 到目前为止,这是工作 - 但我想知道,如果这仅仅是运气,或者如果它被专门使用于(ANSI)SQL规范解决。

IE浏览器ANSI SQL(并由此推测数据库)保证列的顺序返回的SELECT *语句?

我使用PostgreSQL 8.4作为我的后端数据库

  • 是的,我知道,用手工制作的SQL语句与ORM失败的ORM的目的,但需要一定...

Answer 1:

让我们考虑一下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 * ,勇往直前!



文章来源: column order in SELECT * statement - guaranteed?