1

I am not able to create table like/as with constraints and default values from another table that already exists.

I have tried following

$sql = "CREATE TABLE schemas.a AS TABLE schemas.b";

This creates the table but no constraint or default value is copied.

$sql = "CREATE TABLE schemas.a (LIKE schemas.b INCLUDING CONSTRAINTS)";

This creates the table with not null constraint only. Still the primary key constraint and the default value is not being transferred.

Coding used in php

$sql = "CREATE TABLE schemas.a (LIKE schemas.b INCLUDING CONSTRAINTS)";
pg_query($con, $sql);  //This is in the PHP

I want to create the table with all the constraints (primary, unique, not null) and default value that are set.

3
  • The code works outside of PHP? Not a postgresql user but seems strange that the behavior is related to PHP. Commented Oct 3, 2019 at 23:46
  • This has nothing to do with php, it is just about the PostgreSQL CREATE TABLE command. Commented Oct 4, 2019 at 2:23
  • CREATE TABLE Database.NewTableName SELECT * FROM Database.ExistingTable This will create a copy of your table including structure (minus the Primary Key link which you will want to set yourself after you copy it. But this is a FAST way to duplicate a table that is similar to the new one you want to make, and then you can just make the edits to that table. Commented Oct 25, 2022 at 19:05

1 Answer 1

1

Try the following sql:

CREATE TABLE schemas.a (
    LIKE schemas.b
        INCLUDING ALL
);

For further information about the CREATE TABLE command have a look into the documentation: https://www.postgresql.org/docs/current/sql-createtable.html (Perhaps you need to switch to your version. Search for like_option to find the relevant information on the page.)

Sign up to request clarification or add additional context in comments.

1 Comment

Don't know the problem but this work. Earlier i tried something like this but hit with an error. INCLUDING ALL works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.