Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get table schema in Redshift

Hello I am trying to retrieve the schema of an existing table. I am mysql developer and am trying to work with amazon redshift. How can I export the schema of an existing table. In mysql we can use the show create table command.

SHOW CREATE TABLE tblName;
like image 573
user3277217 Avatar asked Apr 30 '14 03:04

user3277217


People also ask

How do you find the schema of a Redshift table?

To view a list of all schemas, query the PG_NAMESPACE system catalog table: select * from pg_namespace; To view a list of tables that belong to a schema, query the PG_TABLE_DEF system catalog table. For example, the following query returns a list of tables in the PG_CATALOG schema.

How do you get the DDL on a Redshift table?

You can recreate the table/schema DDL by running scripts called v_generate_tbl_ddl. sql and v_generate_schema_ddl. sql. The scripts can be downloaded from amazon-redshift-utils, which is part of the Amazon Web Services - Labs git hub repository.

What is PG_TABLE_DEF?

Stores information about table columns. PG_TABLE_DEF only returns information about tables that are visible to the user. If PG_TABLE_DEF does not return the expected results, verify that the search_path parameter is set correctly to include the relevant schemas.


1 Answers

Recently I wrote a python script to clone table schemas between redshift clusters. If you only want the columns and column types of a table, you can do it via:

select column_name,
  case
    when data_type = 'integer' then 'integer'
    when data_type = 'bigint' then 'bigint'
    when data_type = 'smallint' then 'smallint'
    when data_type = 'text' then 'text'
    when data_type = 'date' then 'date'
    when data_type = 'real' then 'real'
    when data_type = 'boolean' then 'boolean'
    when data_type = 'double precision' then 'float8'
    when data_type = 'timestamp without time zone' then 'timestamp'
    when data_type = 'character' then 'char('||character_maximum_length||')'
    when data_type = 'character varying' then 'varchar('||character_maximum_length||')'
    when data_type = 'numeric' then 'numeric('||numeric_precision||','||numeric_scale||')'
    else 'unknown'
  end as data_type,
  is_nullable,
  column_default
 from information_schema.columns
 where table_schema = 'xxx' and table_name = 'xxx' order by ordinal_position
;

But if you need the compression types and distkey/sortkeys, you need to query another table:

select * from pg_table_def where tablename = 'xxx' and schemaname='xxx';
like image 160
ciphor Avatar answered Sep 27 '22 18:09

ciphor