9

I know I can do something like this:

CREATE TABLE new_table AS (
    SELECT field1, field2, field3
    FROM my_table
)

I'm wondering how do I add more columns to this create table SQL, that are not from my_table, but instead ones that I would write my self and which would be unique to this new_table only.

I know I could just make the table with the above SQL and then additionaly (after the command is completed) add the necessary columns, but am wondering if this all could be done in one command, maybe something like this (tried it like that, but didn't work):

CREATE TABLE new_table AS (
    (SELECT field1, field2, field3
    FROM my_table),
    additional_field1 INTEGER NOT NULL DEFAULT 1,
    additional_field2 VARCHAR(20) NOT NULL DEFAULT 1
)
3
  • Do you want empty table new_table with this structure? Sep 10, 2012 at 7:19
  • no, I don't want an empty table, i wan't the table to be populated with the fields from the table my_table and additionaly I want to add my fields which, will be default to some value (just added DEFAULT to my sql example above)
    – Nikola
    Sep 10, 2012 at 7:23
  • Updated answer should work for you.
    – Omesh
    Sep 10, 2012 at 7:48

1 Answer 1

9

You can also explicitly specify the data type for a generated column:

See Create Table Select Manual

CREATE TABLE new_table
(
 additional_field1 INTEGER NOT NULL DEFAULT 1,
 additional_field2 VARCHAR(20) NOT NULL DEFAULT 1
)
AS
(
 SELECT id, val,
        1 AS additional_field1,
        1 AS additional_field2
 FROM my_table
);

Example: SQLFiddle

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.