CREATE TABLE AS with PRIMARY KEY in one statement (PostgreSQL)

PostgresqlPrimary KeyCreate Table

Postgresql Problem Overview


Is there a way to set the PRIMARY KEY in a single "CREATE TABLE AS" statement?

Example - I would like the following to be written in 1 statement rather than 2:

 CREATE TABLE "new_table_name" AS SELECT a.uniquekey, a.some_value + b.some_value FROM "table_a" AS a, "table_b" AS b WHERE a.uniquekey=b.uniquekey;
 ALTER TABLE "new_table_name" ADD PRIMARY KEY (uniquekey);

Is there a better way of doing this in general (assume there are more than 2 tables, e.g. 10)?

Postgresql Solutions


Solution 1 - Postgresql

According to the manual: create table and create table as you can either:

  • create table with primary key first, and use select into later
  • create table as first, and use add primary key later

But not both create table as with primary key - what you wanted.

Solution 2 - Postgresql

If you want to create a new table with the same table structure of another table, you can do this in one statement (both creating a new table and setting the primary key) like this:

create table mytable_clone (like mytable including defaults including constraints including indexes);

Solution 3 - Postgresql

No, there is no shorter way to create the table and the primary key.

Solution 4 - Postgresql

See the command below, it will create a new table with all the constraints and with no data. Worked in postgres 9.5

CREATE TABLE IF NOT EXISTS <ClonedTableName>(like <OriginalTableName> including all)

Solution 5 - Postgresql

well in mysql ,both is possible in one command

the command is

create table new_tbl (PRIMARY KEY(`id`)) as select * from old_tbl;

where id is column with primary key of old_tbl

done...

Solution 6 - Postgresql

You may do this way

CREATE TABLE IOT (EMPID,ID,Name, CONSTRAINT PK PRIMARY KEY( ID,EMPID)) 
 ORGANIZATION INDEX NOLOGGING COMPRESS 1 PARALLEL 4
AS SELECT 1 as empid,2 id,'XYZ' Name FROM dual;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimYView Question on Stackoverflow
Solution 1 - PostgresqlpeenutView Answer on Stackoverflow
Solution 2 - PostgresqlfrancsView Answer on Stackoverflow
Solution 3 - Postgresqla_horse_with_no_nameView Answer on Stackoverflow
Solution 4 - Postgresqluser1188867View Answer on Stackoverflow
Solution 5 - PostgresqlkaushikCView Answer on Stackoverflow
Solution 6 - Postgresqluser5198207View Answer on Stackoverflow