Select datatype of the field in postgres
How do I get datatype of specific field from table in postgres ? For example I have the following table, student_details ( stu_id integer, stu_name varchar(30 ), joined_date timestamp );
In this using the field name / or any other way, I need to get the datatype of the specific field. Is there any possibility ?
Solution 1:
You can get data types from the information_schema (8.4 docs referenced here, but this is not a new feature):
=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
column_name | data_type
--------------------+-----------
id | integer
default_printer_id | integer
master_host_enable | boolean
(3 rows)
Solution 2:
You can use the pg_typeof() function, which also works well for arbitrary values.
SELECT pg_typeof("stu_id"), pg_typeof(100) from student_details limit 1;
Solution 3:
Try this request :
SELECT column_name, data_type FROM information_schema.columns WHERE
table_name = 'YOUR_TABLE' AND column_name = 'YOUR_FIELD';
Solution 4:
run psql -E
and then \d student_details
Solution 5:
If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:
select column_name,
case
when domain_name is not null then domain_name
when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
else data_type
end as myType
from information_schema.columns
where table_name='test'
with result:
column_name | myType
-------------+-------------------
test_id | test_domain
test_vc | varchar(15)
test_n | numeric(15,3)
big_n | bigint
ip_addr | inet