mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Swich Non-Castable Column Type With Using Clause as a Postgres 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://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)
|
||||
|
||||
@@ -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.
|
||||
Reference in New Issue
Block a user