Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table as select statement primary key in oracle

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);
like image 421
absolute Avatar asked Sep 29 '19 11:09

absolute


People also ask

Can we CREATE TABLE name as table in Oracle?

In Oracle, CREATE TABLE statement is used to create a new table in the database. To create a table, you have to name that table and define its columns and datatype for each column.


Video Answer


2 Answers

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;

Here is a demo

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.

like image 147
Nick Krasnov Avatar answered Sep 24 '22 22:09

Nick Krasnov


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;
like image 28
Praveen Deshmukh Avatar answered Sep 22 '22 22:09

Praveen Deshmukh