Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 778
TimY Avatar asked Jun 24 '12 09:06

TimY


People also ask

How do I add a primary key to an existing table in PostgreSQL?

In PostgreSQL, a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement. You use the ALTER TABLE statement in PostgreSQL to add or drop a primary key.

Can a Postgres table have multiple primary keys?

how can i use multiple primary keys in postgres ? You can't. It's an oxymoron - the definition of a primary key is that it's the primary key, singular. You can't have more than one.

How do I create a composite primary key in PostgreSQL?

Composite Primary Key's Syntax in PostgreSQL We use the “PRIMARY KEY” keyword with a bracket in which we write the columns' names separated with commas to specify them as a composite primary key.


2 Answers

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.

like image 155
peenut Avatar answered Sep 22 '22 19:09

peenut


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); 
like image 22
francs Avatar answered Sep 19 '22 19:09

francs