I need to get the name of the columns that make up a table in postgres, to perform an advanced search according to the selection of columns that the user selects.
Is there a query to get the names of the columns of a table in PostgreSQL?
I need to get the name of the columns that make up a table in postgres, to perform an advanced search according to the selection of columns that the user selects.
Is there a query to get the names of the columns of a table in PostgreSQL?
The schema information could be used to return the name of the columns of a specific table, accessing specifically to information_schema.columns
that has the column names of the tables.
The query in question would be:
SELECT column_name --Seleccionamos el nombre de columna
FROM information_schema.columns --Desde information_schema.columns
WHERE table_schema = 'public' --En el esquema que tenemos las tablas en este caso public
AND table_name = 'tu_tabla' --El nombre de la tabla especifica de la que deseamos obtener información
However, using information_schema.columns
is not the best form if you work on Postgresql, since it is slower. See for example this answer .
Here is another possibility, using pg_attribute
, it's faster and more complete. In the link you can see all the information you can get with it.
Here is an example of some interesting information from our table:
CREATE TABLE account(
user_id serial PRIMARY KEY,
username VARCHAR (50) UNIQUE NOT NULL,
password VARCHAR (50) NOT NULL,
email VARCHAR (355) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
last_login TIMESTAMP
);
SELECT DISTINCT
a.attnum as no,
a.attname as nombre_columna,
format_type(a.atttypid, a.atttypmod) as tipo,
a.attnotnull as notnull,
com.description as descripcion,
coalesce(i.indisprimary,false) as llave_primaria,
def.adsrc as default
FROM pg_attribute a
JOIN pg_class pgc ON pgc.oid = a.attrelid
LEFT JOIN pg_index i ON
(pgc.oid = i.indrelid AND i.indkey[0] = a.attnum)
LEFT JOIN pg_description com on
(pgc.oid = com.objoid AND a.attnum = com.objsubid)
LEFT JOIN pg_attrdef def ON
(a.attrelid = def.adrelid AND a.attnum = def.adnum)
WHERE a.attnum > 0 AND pgc.oid = a.attrelid
AND pg_table_is_visible(pgc.oid)
AND NOT a.attisdropped
AND pgc.relname = 'account' -- Nombre de la tabla
ORDER BY a.attnum;
result
no nombre_columna tipo notnull descripcion llave_primaria default
1 1 user_id integer True NULL True nextval('account_user_id_seq'::regclass)
2 2 username character varying(50) True NULL False NULL
3 3 password character varying(50) True NULL False NULL
4 4 email character varying(355) True NULL False NULL
5 5 created_on timestamp without time zone True NULL False NULL
6 6 last_login timestamp without time zone False NULL False NULL