Tuesday 8 August 2023

create table with same schema in postgres

Create table with same schema in postgres:

To create a table with the same schema as an existing table, you can use the LIKE clause in the CREATE TABLE statement. The LIKE clause specifies the name of the source table that you want to copy the schema from. For example, if you have a table named customers and you want to create a new table named customers_backup with the same schema, you can use: 


CREATE TABLE customers_backup (LIKE customers);

In the below screenshot, we can see we have created a new table like pc_LinkAttachment


This will create a new table with the same column names, data types, and constraints as the source table. However, it will not copy the indexes, triggers, rules, or default values from the source table. If you want to include those as well, you can use some optional parameters after the LIKE clause. For example, if you want to copy the indexes and default values, you can use:


CREATE TABLE customers_backup (LIKE customers INCLUDING INDEXES INCLUDING DEFAULTS);

You can also use EXCLUDING or INCLUDING ALL to specify what to exclude or include from the source table. For more details on the syntax and options of the LIKE clause, you can refer to the Postgre documentation

hope this helps you create a table with the same schema in PostgreSQL.