Using CTAS statement maintaining the original primary key - Synapse SQL pool

pmscorca 1,032 Reputation points
2024-03-16T17:24:39.61+00:00

Hi,

In a Synapse dedicated SQL pool is it possible to use the CREATE TABLE AS SELECT statement maintaining the original primary of the source table?

Thanks

Azure Synapse Analytics
Azure Synapse Analytics
An Azure analytics service that brings together data integration, enterprise data warehousing, and big data analytics. Previously known as Azure SQL Data Warehouse.
5,253 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Azar 26,820 Reputation points MVP
    2024-03-16T17:32:55.7366667+00:00

    Hey there pmscorca

    Thats a good question and thanks for using QandA platform

    I guess yees, you can use the CREATE TABLE AS SELECT (CTAS) statement to create a new table while maintaining the original primary key of the source table. but, you need to make sure that you define the primary key constraint in the new table. like this (see below code)

    CREATE TABLE new_table
    WITH
    (
        DISTRIBUTION = HASH(primary_key_column) 
    )
    AS
    SELECT *
    FROM source_table
    WHERE 1=0; 
    ALTER TABLE new_table ADD CONSTRAINT PK_new_table PRIMARY KEY (primary_key_column);
    INSERT INTO new_table
    SELECT *
    FROM source_table;
    
    

    If this helps kindly accept the answer thanks much.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.