HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

How to CREATE TABLE ... LIKE without the NOT NULL Constraints?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withouttheconstraintscreatenulllikehownottable

Problem

I'm trying recreate a table's structure inside a function by using some dynamic SQL.

EXECUTE 'CREATE TABLE ' || my_table_name || '_bk' ||
    ' (like ' || _my_table_name || ')';


That will be similar to:

CREATE TABLE my_table_bk
(like my_table);


But I need to discard all constraints. Using EXCLUDING CONSTRAINTS in the Like Options, it still copy the NOT NULL Constraints (Documentation confirms this behavior):

CREATE TABLE my_table_bk
(like my_table EXCLUDING CONSTRAINTS);


The question is, how can I recreate the table structure without the NOT NULL constraints, or, in alternative, remove all NOT NULL constraints in a table?

Solution

Try this:

CREATE TABLE my_table_bk
AS
  SELECT *
  FROM my_table
  WHERE false;


Or, you can append LIMIT 0 instead of the WHERE clause.

This will create a table my_table_bk with the same structure as my_table without constraints and without data.

Code Snippets

CREATE TABLE my_table_bk
AS
  SELECT *
  FROM my_table
  WHERE false;

Context

StackExchange Database Administrators Q#67852, answer score: 24

Revisions (0)

No revisions yet.