1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-05 16:18:01 +00:00

Add Add ON DELETE CASCADE To Foreign Key Constraint as a postgres til

This commit is contained in:
jbranchaud
2016-04-22 15:44:45 -05:00
parent c49beb59e4
commit e5f338eeb4
2 changed files with 32 additions and 1 deletions

View File

@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
warrant a full blog post. These are mostly things I learn by pairing with warrant a full blog post. These are mostly things I learn by pairing with
smart people at [Hashrocket](http://hashrocket.com/). smart people at [Hashrocket](http://hashrocket.com/).
_399 TILs and counting..._ _400 TILs and counting..._
--- ---
@@ -167,6 +167,7 @@ _399 TILs and counting..._
### PostgreSQL ### PostgreSQL
- [A Better Null Display Character](postgres/a-better-null-display-character.md) - [A Better Null Display Character](postgres/a-better-null-display-character.md)
- [Add ON DELETE CASCADE To Foreign Key Constraint](postgres/add-on-delete-cascade-to-foreign-key-constraint.md)
- [Adding Composite Uniqueness Constraints](postgres/adding-composite-uniqueness-constraints.md) - [Adding Composite Uniqueness Constraints](postgres/adding-composite-uniqueness-constraints.md)
- [Aggregate A Column Into An Array](postgres/aggregate-a-column-into-an-array.md) - [Aggregate A Column Into An Array](postgres/aggregate-a-column-into-an-array.md)
- [Auto Expanded Display](postgres/auto-expanded-display.md) - [Auto Expanded Display](postgres/auto-expanded-display.md)

View File

@@ -0,0 +1,30 @@
# Add ON DELETE CASCADE To Foreign Key Constraint
The `alter table` command lets you do quite a bit. But when it comes to
altering existing constraints, there is not much you can do. If you want to
add an `on delete cascade` to an existing foreign key constraint, you are
going to need two statements.
The first statement will drop the constraint and the second statement will
recreate it with the addition of the `on delete` clause. Furthermore, you'll
want to do this in a transaction to ensure the integrity of your data during
the transition between indexes.
Here is an example:
```sql
begin;
alter table
drop constraint orders_customer_id_fkey;
alter table
add constraint orders_customer_id_fkey
foreign key (customer_id)
references customers (id)
on delete cascade;
commit;
```
[source](http://stackoverflow.com/questions/10356484/how-to-add-on-delete-cascade-constraints)