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

Hom*_*lli 7 sql postgresql sqlalchemy ansi-sql

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

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

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

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

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

Luk*_*der 14

让我们考虑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.
Run Code Online (Sandbox Code Playgroud)

所以,换句话说,是的,SQL标准规定了列将根据它们的序数位置进行投影T.请注意,当您<table expression>包含几个涉及JOIN .. USINGNATURAL JOIN子句的表时,事情会变得有点棘手.但是,从简单的表中进行选择时,假设订单符合预期,您可能会很好.

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

General Rules
     5) [...] The ordinal position included
        in the column descriptor is equal to the degree of T. [...]
Run Code Online (Sandbox Code Playgroud)

然后在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>".
Run Code Online (Sandbox Code Playgroud)

有相当依赖的正式规范其他几个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>`)
Run Code Online (Sandbox Code Playgroud)

特别是Postgres非常符合标准,所以如果您真的想要SELECT *,请继续!

  • @basgys:即使SQL标准实际指定了,我也绝不会依赖任何订单(顺便说一下:Postgres不**支持`ADD COLUMN ... AFTER`) (2认同)