简体   繁体   中英

Adding NOT NULL constraint to Cloud Spanner table

If a Cloud Spanner table is created with nullable columns, is it possible to add a NOT NULL constraint on a column without recreating the table?

You can add a NOT NULL constraint to a non-key column. You must first ensure that all rows actually do have values for the column. Spanner will scan the data to verify before fully applying the NOT NULL constraint. More information about how to alter tables is here and here .

However, you can not add such a constraint to a key column. That kind of change would require rewriting all the data in the table, because the nullness of the key affects how the data is encoded. The only option for making that change is to create a new table that's set up the way you want, make code changes to support using both tables temporarily, gradually move the data from the old table to the new table, and eventually change the code to use only the new table and drop the old table. If you further then wanted the original table name, you'd have to do the whole thing again.

Unfortenately there is not way to add not null column

The way to do it:

1 add nullable column

ALTER TABLE table1 ADD COLUMN column1 STRING(255)
  1. UPDATE table1.column1, SET NOT NULL VALUE to the column (if the table is not empty).
UPDATE TABLE table1 SET column1 = "<GENERATED DATA>"
  1. Add constraint
ALTER TABLE table1 ADD COLUMN column1 STRING(255) NOT NULL

Thanks.

Creating a nullable column in spanner on an existing table is typically a three step process...

# add new column to table
ALTER TABLE <table_name> ADD COLUMN <column_name> <value_type>;

# create default values
UPDATE <table_name> SET <column_name>=<default_value> WHERE TRUE;

# add constraint
ALTER TABLE <table_name> ALTER COLUMN <column_name> <value_type> NOT NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM