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
)
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
You can add multiple columns to an SQL table using the ALTER TABLE syntax. To do so, specify multiple columns to add after the ADD keyword. Separate each column you want to add using a comma.
A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. The new table has the same column definitions. All columns or specific columns can be selected.
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With