Refer to the column by its number (index)

I want to make a selection using the index (number) of a column. I tried:

select 1 from "user"
select '1' from "user"

but they do not do what I expect.

+7
source share
3 answers

You cannot do this in postgres. Choosing a literal (e.g., 1or '1') will simply return its value. The only place where such indexes are allowed is in the sentence order by, and even there they do not relate to the order of the columns in the table, but in the selection list:

SELECT   col1, col2, col3
FROM     my_table
ORDER BY 1

EDIT:
order by <some index> select *, , . , * , , order by. , , select, .

EDIT2:
@klin, postgres 'group by :

SELECT   col1, COUNT(*)
FROM     my_table
GROUP BY 1
+12

( ), - :

SELECT uno FROM _your_table_ as t(uno);

!..

1, - :

SELECT "1" FROM _your_table_ as t("1");

... , !!!!

+1

There are several ways to do this in PostgreSQL. The simplest (I think) is to create a "function". Start with the PG tutorial for working examples. This is pretty easy. You can choose from different languages. The lines here are for pl / pgsql, but you will understand the idea:

First, you extract the column name from the system directory, doing something like this:

attname := select distinct attname from pg_attribute,pg_class where attrelid = pg_class.oid and attnum = 1 and pg_class.relname='user';

Then you combine this into an SQL statement:

EXECUTE 'SELECT ' || attname || ' FROM ...
0
source

Source: https://habr.com/ru/post/1541006/


All Articles