1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00

Add Truncate Tables With Dependants as a postgres til.

This commit is contained in:
jbranchaud
2015-11-09 22:51:07 -06:00
parent 3e599c4936
commit 74e4bfeb15
2 changed files with 38 additions and 0 deletions

View File

@@ -130,6 +130,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
- [Timestamp Functions](postgres/timestamp-functions.md)
- [Toggling The Pager In PSQL](postgres/toggling-the-pager-in-psql.md)
- [Truncate All Rows](postgres/truncate-all-rows.md)
- [Truncate Tables With Dependants](postgres/truncate-tables-with-dependants.md)
- [Turning Timing On](postgres/turning-timing-on.md)
- [Types By Category](postgres/types-by-category.md)
- [Use Argument Indexes](postgres/use-argument-indexes.md)

View File

@@ -0,0 +1,37 @@
# Truncate Tables With Dependants
In [Truncate All Rows](postgres/truncate-all-rows.md), I talked about how
postgres's `truncate` can be used to quickly delete all rows in a table. In
practice this alone won't be very useful though, because tables usually have
other tables that depend on them via foreign keys. If you have tables `A`
and `B` where `B` has a foreign key referencing `A`, then trying to truncate
`A` will result in something like this:
```sql
> truncate A;
ERROR: cannot truncate a table referenced in a foreign key constraint
```
Fortunately, `truncate` has some tricks up its sleeve.
If you know two tables are tied together via a foreign key constraint, you
can just truncate both of them at once:
```sql
> truncate A, B;
TRUNCATE TABLE;
```
If many tables are tied together in this way and you are looking to throw
all of it out, then a simpler approach is to cascade the truncation:
```
> truncate A cascade;
NOTICE: truncate cascades to table "B"
TRUNCATE TABLE
```
Use these with care and potentially within transactions because your data
will go bye bye.
h/t Dillon Hafer and Jack Christensen