Skip to content

Instantly share code, notes, and snippets.

@vbilopav
Created April 11, 2018 10:53
Show Gist options
  • Save vbilopav/eaabe3c767f9a091ac0ec75dc0481df5 to your computer and use it in GitHub Desktop.
Save vbilopav/eaabe3c767f9a091ac0ec75dc0481df5 to your computer and use it in GitHub Desktop.
select
t.table_name,
c.column_name,
c.data_type ||
case when c.character_maximum_length is not null
then '(' || cast(c.character_maximum_length as varchar) || ')'
else case when c.numeric_precision is not null
then '(' || cast(c.numeric_precision as varchar) || ',' || cast(c.numeric_precision_radix as varchar) || ')'
|| case when coalesce(c.numeric_scale, 0) = 0 then '' else ',' || cast(c.numeric_scale as varchar) || ')' end
else ''
end
end as type,
case when c.is_nullable = 'YES' then 'NULL' when c.is_nullable = 'NO' then 'NOT NULL' else '' end as nullable,
case when c.column_default like 'next%' then 'auto increment' else c.column_default end as default
from (
select t1.table_name as table_name_id, t1.table_name
from information_schema.tables t1
where t1.table_schema = 'public'
union all
select t2.table_name as table_name_id, null as table_name
from information_schema.tables t2
where t2.table_schema = 'public'
order by table_name_id, table_name nulls first
) t
left outer join
information_schema.columns c
on t.table_name = c.table_name and c.table_schema = 'public'
order by table_name_id, table_name nulls first, c.ordinal_position
select
t.table_name,
c.column_name,
c.data_type ||
case when c.character_maximum_length is not null
then '(' || cast(c.character_maximum_length as varchar) || ')'
else case when c.numeric_precision is not null
then '(' || cast(c.numeric_precision as varchar) || ',' || cast(c.numeric_precision_radix as varchar) || ')'
|| case when coalesce(c.numeric_scale, 0) = 0 then '' else ',' || cast(c.numeric_scale as varchar) || ')' end
else ''
end
end as type,
case when c.is_nullable = 'YES' then 'NULL' when c.is_nullable = 'NO' then 'NOT NULL' else '' end as nullable,
case when c.column_default like 'next%' then 'auto increment' else c.column_default end as default
from (
select t1.table_name as table_name_id, t1.table_name
from information_schema.tables t1
where t1.table_schema = 'public'
union all
select t2.table_name as table_name_id, null as table_name
from information_schema.tables t2
where t2.table_schema = 'public'
order by table_name_id, table_name nulls first
) t
left outer join
information_schema.columns c
on t.table_name = c.table_name and c.table_schema = 'public'
order by table_name_id, table_name nulls first, c.ordinal_position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment