SQL >> Database >  >> RDS >> PostgreSQL

Kolomvolgorde bij SELECT *: is die gegarandeerd?

Laten we de SQL-standaard bekijken, sectie 7.9 <query specification>:

https://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. 

Met andere woorden: ja, de standaard schrijft voor dat kolommen worden geprojecteerd volgens hun ordinale positie in T.

Wel wordt het ingewikkelder wanneer je <table expression> uit meerdere tabellen bestaat en JOIN ... USING of NATURAL JOIN gebruikt. Selecteer je uit één eenvoudige tabel, dan mag je er redelijk op vertrouwen dat de volgorde is zoals verwacht.

Ordinale positie

Voor tabellen wordt de betekenis van ordinal position within T verderop uitgelegd in 11.4 <column definition>:

General Rules 5) [...] The ordinal position included in the column descriptor is equal to the degree of T. [...] 

En in 11.11 <add column definition> (voor 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>". 

Meer SQL-statements en clauses steunen op de formele definitie van ordinal positions, bijvoorbeeld:

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 is behoorlijk conform de standaard, dus als je echt SELECT * wilt gebruiken: ga je gang.

  1. Dynamische kolomnamen gebruiken in een PL/pgSQL UPDATE

  2. Geeft SELECT altijd rijen gesorteerd op primary key?

  3. Oracle identity-kolommen en INSERT INTO SELECT

  4. SQL SELECT uitgelegd met voorbeelden