mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Use Rename To Hot Swap Two Tables 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://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1222 TILs and counting..._
|
||||
_1223 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -678,6 +678,7 @@ _1222 TILs and counting..._
|
||||
- [Use A psqlrc File For Common Settings](postgres/use-a-psqlrc-file-for-common-settings.md)
|
||||
- [Use Argument Indexes](postgres/use-argument-indexes.md)
|
||||
- [Use Not Valid To Immediately Enforce A Constraint](postgres/use-not-valid-to-immediately-enforce-a-constraint.md)
|
||||
- [Use Rename To Hot Swap Two Tables](postgres/use-rename-to-hot-swap-two-tables.md)
|
||||
- [Using Expressions In Indexes](postgres/using-expressions-in-indexes.md)
|
||||
- [Using Intervals To Offset Time](postgres/using-intervals-to-offset-time.md)
|
||||
- [Who Is The Current User](postgres/who-is-the-current-user.md)
|
||||
|
||||
34
postgres/use-rename-to-hot-swap-two-tables.md
Normal file
34
postgres/use-rename-to-hot-swap-two-tables.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Use Rename To Hot Swap Two Tables
|
||||
|
||||
The [`alter
|
||||
table`](https://www.postgresql.org/docs/current/sql-altertable.html) command
|
||||
can be used to [rename a
|
||||
table](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-rename-table/).
|
||||
Because it is changing the name of a reference rather than actually moving any
|
||||
data around, it is very fast.
|
||||
|
||||
We can exploit the speed of a _rename_ to hot swap two tables. This is useful
|
||||
for a situation where we've created an identical table with a small fraction of
|
||||
the data of the original table. By hot swapping them, we've exchanged the large
|
||||
table for a smaller one without our application code noticing anything
|
||||
happened.
|
||||
|
||||
Let's assume we have a massive `events` table and then a much smaller
|
||||
`new_events` table with the same structure.
|
||||
|
||||
The following transaction will swap those two tables in the blink of an eye.
|
||||
|
||||
```sql
|
||||
begin;
|
||||
|
||||
alter table events rename to old_events;
|
||||
alter table new_events rename to events;
|
||||
|
||||
commit;
|
||||
```
|
||||
|
||||
The resulting `old_events` table can then be deleted at our convenience.
|
||||
|
||||
The other nice thing about this approach is that, before deleting `old_events`,
|
||||
you can easily and quickly swap them back using the same approach. It is always
|
||||
a comfort when huge changes like this are easy to reverse if necessary.
|
||||
Reference in New Issue
Block a user