select * from foo order by 2
Order of the fields when doing "select *" may be guaranteed (I don't know) but they have been dependent on when the feild was added to the database on every system I have worked with, and sometimes patches are applied in diffrent orders on diffrent databases. AND 1=1
AND this script has the table information stored in dicts in the {column name: column type} form
AND this script is run by a python version where the dict order is undefined
you will get funny outputs from your queries that break production deployments in subtle and unique ways.So yeah, just use column names (and name your computed columns!).
Edit -- this is wrong see below
> Each expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.
> The ordinal number refers to the ordinal (left-to-right) position of the output column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it is always possible to assign a name to an output column using the AS clause.
(emphasis mine)
https://www.postgresql.org/docs/current/sql-select.html#SQL-...
select a.1, a.2, a.3, ... a.10 GROUP BY 1,2,3,4,5,6,7,8,9,10
conveys the intent more clearly than listing out all the column names
select a || 'baz', avg(b) from foo group by 1 order by 2;
... meaning 'order by 2' would order it by the values in the column named '2', but which wasn't selected.
SELECT 'val' AS 2
Instead you must escape the identifier with double quotes: SELECT 'val' AS "2"
So there is no ambiguity on that front in the ORDER BY clause. Either you have `ORDER BY 2`, which means order by the second column, or you have `ORDER BY "2"`, which means order by the column named "2".