CREATE TABLE AS

Function

CREATE TABLE AS creates a table based on the results of a query.

CREATE TABLE AS creates a table and fills it with the data returned by the SELECT statement. The columns in the new table match the names and data types of the output fields from the SELECT statement. Except that you can override the SELECT output column names by giving an explicit list of new column names.

CREATE TABLE AS queries once the source table and writes data in the new table. The query result view changes when the source table changes. In contrast, a view re-evaluates its defining SELECT statement whenever it is queried.

Precautions

Syntax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
CREATE [ UNLOGGED ] TABLE table_name
    [ (column_name [, ...] ) ]
    [ WITH ( {storage_parameter = value} [, ... ] ) ]
    [ COMPRESS | NOCOMPRESS ]
    
    [ DISTRIBUTE BY { REPLICATION | ROUNDROBIN | { [HASH ] ( column_name ) } } ]
    
    [ COMMENT [=] 'text' ]
    AS query
    [ WITH [ NO ] DATA ];

Parameter Description

Examples

Create the CUSTOMER table:

1
2
3
4
5
6
7
8
9
DROP TABLE IF EXISTS CUSTOMER;
CREATE TABLE CUSTOMER
(    
    C_CUSTKEY     BIGINT NOT NULL CONSTRAINT C_CUSTKEY_pk PRIMARY KEY  , 
    C_NAME        VARCHAR(25)  , 
    C_ADDRESS     VARCHAR(40)  , 
    C_NATIONKEY   INT NOT NULL  CHECK (C_NATIONKEY > 0)  
)
DISTRIBUTE BY HASH(C_CUSTKEY);

Create the store_returns_t1 table and insert numbers that are greater than 4795 in the CUSTOMER column of the CUSTOMER table:

1
CREATE TABLE store_returns_t1 AS SELECT * FROM CUSTOMER WHERE C_CUSTKEY > 4795;

Copy store_returns to create the store_returns_t2 table:

1
CREATE TABLE store_returns_t2 AS table store_returns;

Helpful Links

CREATE TABLE, SELECT