mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Change Existing Column To Not Null as a MySQL TIL
This commit is contained in:
@@ -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).
|
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
|
### 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)
|
- [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)
|
- [Display Output In A Vertical Format](mysql/display-output-in-a-vertical-format.md)
|
||||||
- [Doing Date Math](mysql/doing-date-math.md)
|
- [Doing Date Math](mysql/doing-date-math.md)
|
||||||
|
|||||||
27
mysql/change-existing-column-to-not-null.md
Normal file
27
mysql/change-existing-column-to-not-null.md
Normal file
@@ -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)
|
||||||
Reference in New Issue
Block a user