Reputation: 63
Is it possible to specify which is the primary key on creating table as select statement? My aim is to include the declaration of primary key on the create table not modifying the table after the creation.
CREATE TABLE suppliers
AS (SELECT company_id, address, city, state, zip
FROM companies
WHERE company_id < 5000);
Upvotes: 5
Views: 8344
Reputation: 21
Yes, it's possible.You can try referring below example.
create table student (rollno ,student_name,score , constraint pk_student primary key(rollno,student_name))
as
select empno,ename,sal
from emp;
Upvotes: 2
Reputation: 57
You can create Suppliers table explicitly and if any column have primary key in companies table, then copy that structure from companies table.
Or
Create a same column defining primary key that you want and copy that column from companies table!
Upvotes: -1
Reputation: 27261
Yes, it's possible. You would need to specify columns explicitly:
CREATE TABLE suppliers (
company_id primary key,
address,
city,
state,
zip
)
AS
SELECT company_id, address, city, state, zip
FROM companies
WHERE company_id < 5000;
Note: in this case primary key constraint will be given a system-generated name. If you want it to have a custom name you'd have to execute alter table suppliers add constraint <<custom constraint name>> primary key(<<primary_key_column_name>>)
after executing(without primary key
specified) CREATE TABLE suppliers..
DDL statement.
Upvotes: 7