I am using an ORM (sqlalchemy) to fetch data from a PG database. I want to avoid specifying all the table column names in my hand crafted SQL statements*.
My assumption so far is that the returned columns are in the order of the DDL statements used to create the db tables. So far this is working – but I want to know if this is merely luck, or if it is specifically addressed in the (ANSI) SQL specification.
i.e. does ANSI SQL (and thus presumably the database) guarantee the order of columns returned in a SELECT * statement?
I am using PostgreSQL 8.4 as my backend db
- yes, I am aware that using hand crafted SQL statements with an ORM defeats the purpose of an ORM, but needs must …
Let’s consider the SQL standard, section
7.9 <query specification>as specified here:http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt
So, in other words, yes, the SQL standard specifies that columns are to be projected according to their ordinal position within
T. Note, that things get a bit tricky, when your<table expression>consists of several tables involvingJOIN .. USINGorNATURAL JOINclauses. However, when selecting from a simple table, you’re probably fine assuming that the order is as expected.For completeness, the meaning of an
ordinal position within Tfor tables is explained further down in11.4 <column definition>:And then in
11.11 <add column definition>(forALTER TABLEstatements)There are quite a few other SQL statements and clauses that depend on the formal specification of
ordinal positionswithin<table expressions>. Some examples:Postgres, in particular, is quite standards-compliant, so if you really want to
SELECT *, go ahead!