1

I am creating table using following way:

CREATE TABLE test AS 
  SELECT    t1.column1, 
            t1.column2, 
            t1.column3, 

            t2.column4 , 
            t2.column6 , 
            t1.column8 
  FROM      table_1 t1
  JOIN table_2 t2 
  ON        t1.column1 = t2.column2 ;

after that I am adding column in newly created table using following alter command

ALTER TABLE test ADD COLUMN New_column1 varchar NOT NULL DEFAULT 0,
              ADD COLUMN New_column2    varchar NOT NULL DEFAULT 0, 
              ;

Now I want to merge both query into One.

How I can do that ?

Thank You

1
  • 1
    Add the new columns as literals to the Select (maybe you need to cast to get the correct data type). Btw, a varchar with a numeric default zero is strange... Commented Jan 11, 2016 at 8:09

2 Answers 2

2

Although its difficult to set the NOT NULL constraint in a CREATE TABLE AS statement, you should still be able to create new columns in the new table in a single SQL statement.

However, you would require a second (Faster) SQL to set the NOT NULL for the two new columns.

SELECT 
    t1.column1, 
    t1.column2, 
    t1.column3, 
    t2.column4, 
    t2.column6, 
    t1.column8, 
    0 AS New_column1, 
    0 AS New_column2
  INTO test
FROM table_1 t1
JOIN table_2 t2 ON t1.column1 = t2.column2;

ALTER TABLE test ALTER COLUMN New_column1 SET DEFAULT NOT NULL;
ALTER TABLE test ALTER COLUMN New_column1 SET DEFAULT NOT NULL;
Sign up to request clarification or add additional context in comments.

Comments

0

There multiple ways available:

1) This will create the table and insert data.

Select * into test from (
SELECT  t1.column1, 
        t1.column2, 
        t1.column3, 
        t2.column4 , 
        t2.column6 , 
        t1.column8 
FROM table_1 t1
JOIN table_2 t2 
ON   t1.column1 = t2.column2
)

3 Comments

Using the non-standard select into is discouraged. It's better to use the standard create table as as shown in the question. This also doesn't answer the question on how to create a new column. Plus it will fail, because the derived table does not have an alias
Thanks @a_horse_with_no_name. I didn't know that SELECT INTO was discouraged. Could you point to any references to that? Would consider that into account hereon if so. Thanks.
From the manual: "The PostgreSQL usage of SELECT INTO to represent table creation is historical. It is best to use CREATE TABLE AS for this purpose in new code"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.