diff --git a/README.md b/README.md index 1ef9e04..3664f31 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://tinyletter.com/jbranchaud). -_1003 TILs and counting..._ +_1004 TILs and counting..._ --- @@ -560,6 +560,7 @@ _1003 TILs and counting..._ - [Special Math Operators](postgres/special-math-operators.md) - [Storing Emails With citext](postgres/storing-emails-with-citext.md) - [String Contains Another String](postgres/string-contains-another-string.md) +- [Switch Non-Castable Column Type With Using Clause](postgres/switch-non-castable-column-type-with-using-clause.md) - [Temporarily Disable Triggers](postgres/temporarily-disable-triggers.md) - [Temporary Tables](postgres/temporary-tables.md) - [Terminating A Connection](postgres/terminating-a-connection.md) diff --git a/postgres/switch-non-castable-column-type-with-using-clause.md b/postgres/switch-non-castable-column-type-with-using-clause.md new file mode 100644 index 0000000..053209e --- /dev/null +++ b/postgres/switch-non-castable-column-type-with-using-clause.md @@ -0,0 +1,34 @@ +# Switch Non-Castable Column Type With Using Clause + +With certain data types, such as from `int` to `bigint` or `timestamptz` to +`timestamp`, there is an automatic type casting that can take place with +existing data. This means Postgres knows how to handle a data type change +like: + +```sql +alter table users + alter column id + set data type bigint; +``` + +With other data types, such as `int` to `uuid`, there is no way for Postgres to +know how to automatically cast it. To change the data type of a column in a +scenario like this, you have to tell Postgres how to handle the conversion with +a `using` clause. + +```sql +alter table users + alter column id + set data type uuid using (gen_random_uuid()); +``` + +In this instance, the `using` clause tells Postgres to ignore the existing +integer `id` value and use the `gen_random_uuid()` function to generate a UUID +value to take its place. + +The `using` clause can also reference the existing column value as part of its +type cast. + +See the [alter table +documentation](https://www.postgresql.org/docs/current/sql-altertable.html) for +more details on this.