From 777239db241b1d614e11116560674dc2a556da92 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 2 Oct 2022 09:53:54 -0500 Subject: [PATCH] Add Change Existing Column To Not Null as a MySQL TIL --- README.md | 3 ++- mysql/change-existing-column-to-not-null.md | 27 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 mysql/change-existing-column-to-not-null.md diff --git a/README.md b/README.md index 5154bad..c8e7d90 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1249 TILs and counting..._ +_1250 TILs and counting..._ --- @@ -522,6 +522,7 @@ _1249 TILs and counting..._ ### MySQL +- [Change Existing Column To Not Null](mysql/change-existing-column-to-not-null.md) - [Default Username And Password For New Instance](mysql/default-username-and-password-for-new-instance.md) - [Display Output In A Vertical Format](mysql/display-output-in-a-vertical-format.md) - [Doing Date Math](mysql/doing-date-math.md) diff --git a/mysql/change-existing-column-to-not-null.md b/mysql/change-existing-column-to-not-null.md new file mode 100644 index 0000000..7ef9d0a --- /dev/null +++ b/mysql/change-existing-column-to-not-null.md @@ -0,0 +1,27 @@ +# Change Existing Column To Not Null + +Let's say you have an existing nullable column. You want to update the schema +to enforce a `not null` constraint on that column. You can do that with an +[`alter table`](https://dev.mysql.com/doc/refman/8.0/en/alter-table.html) DDL +statement. You can do this with the `modify` or `change` option. + +With `modify` you redeclare the column definition with the options that you +want. You'll need to know and specify the existing data type of that column. + +```sql +alter table books modify publication_year int not null; +``` + +It is possible, but clumsy to do this with the `change` option because you +declare the column name twice. That's because `change` is typically used to +rename a column. + +```sql +alter table books change publication_year publication_year int not null; +``` + +If you're updating a column for a table that already contains data, make a plan +to backfill any existing records that have `null` for that column. Every record +will need a value in that column before the `modify` can be applied. + +[source](https://stackoverflow.com/a/6305252/535590)