diff --git a/db/migrate/20170713104829_add_foreign_key_to_merge_requests.rb b/db/migrate/20170713104829_add_foreign_key_to_merge_requests.rb
index 78ff75279679a2734a55fb6c9ff1abdaa23c5256..8a4e106231485a8b20ac7449da8a62d133c8d11f 100644
--- a/db/migrate/20170713104829_add_foreign_key_to_merge_requests.rb
+++ b/db/migrate/20170713104829_add_foreign_key_to_merge_requests.rb
@@ -6,6 +6,14 @@ class AddForeignKeyToMergeRequests < ActiveRecord::Migration
   disable_ddl_transaction!
 
   def up
+    execute <<-SQL.strip_heredoc
+      UPDATE merge_requests SET head_pipeline_id = null
+        WHERE NOT EXISTS (
+          SELECT 1 FROM ci_pipelines
+            WHERE ci_pipelines.id = merge_requests.head_pipeline_id
+        )
+    SQL
+
     unless foreign_key_exists?(:merge_requests, :head_pipeline_id)
       add_concurrent_foreign_key(:merge_requests, :ci_pipelines,
                                  column: :head_pipeline_id, on_delete: :nullify)