12

ORM (sqlalchemy) を使用して PG データベースからデータを取得しています。手作りの SQL ステートメントですべてのテーブル列名を指定することは避けたい*。

これまでのところ、返された列は、db テーブルの作成に使用された DDL ステートメントの順序になっていると想定しています。これまでのところ、これは機能していますが、これが単なる運なのか、それとも (ANSI) SQL 仕様で具体的に対処されているのかを知りたいです。

つまり、ANSI SQL (およびおそらくデータベース) は、SELECT *ステートメントで返される列の順序を保証しますか?

バックエンドデータベースとしてPostgreSQL 8.4を使用しています

  • はい、ORM で手作りの SQL ステートメントを使用すると、ORM の目的が損なわれることは承知していますが、...
4

1 に答える 1

18

7.9 <query specification>ここで指定されている SQL 標準のセクションを考えてみましょう。

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。or句<table expression>を含む複数のテーブルで構成されている場合、少し注意が必要です。ただし、単純なテーブルから選択する場合は、順序が期待どおりであると想定して、おそらく問題ありません。JOIN .. USINGNATURAL JOIN

ordinal position within T完全を期すために、 for テーブルの意味は でさらに説明されてい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>".

ordinal positionswithinの正式な仕様に依存する SQL ステートメントと句は他にもかなりあります<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 *、先に進んでください。

于 2012-07-31T09:48:11.007 に答える