diff --git a/db/migrate/20161130101252_fill_projects_routes_table.rb b/db/migrate/20161130101252_fill_projects_routes_table.rb
index 4f3fe7b03a910099ed8f2f40129ae82b403072e1..56ba6fcdbe35cf1c2a58e5be5e7ead3f7d908a26 100644
--- a/db/migrate/20161130101252_fill_projects_routes_table.rb
+++ b/db/migrate/20161130101252_fill_projects_routes_table.rb
@@ -8,12 +8,20 @@ class FillProjectsRoutesTable < ActiveRecord::Migration
   DOWNTIME_REASON = 'No new projects should be created during data copy'
 
   def up
-    execute <<-EOF
-      INSERT INTO routes
-      (source_id, source_type, path)
-      (SELECT projects.id, 'Project', concat(namespaces.path, '/', projects.path) FROM projects
-      INNER JOIN namespaces ON projects.namespace_id = namespaces.id)
-    EOF
+    if Gitlab::Database.postgresql?
+      execute <<-EOF
+        INSERT INTO routes (source_id, source_type, path)
+        (SELECT DISTINCT ON (namespaces.path, projects.path) projects.id, 'Project', concat(namespaces.path, '/', projects.path)
+         FROM projects INNER JOIN namespaces ON projects.namespace_id = namespaces.id
+         ORDER BY namespaces.path, projects.path, projects.id DESC)
+      EOF
+    else
+      execute <<-EOF
+        INSERT INTO routes (source_id, source_type, path)
+        (SELECT projects.id, 'Project', concat(namespaces.path, '/', projects.path)
+         FROM projects INNER JOIN namespaces ON projects.namespace_id = namespaces.id)
+      EOF
+    end
   end
 
   def down
diff --git a/db/migrate/20161202152031_remove_duplicates_from_routes.rb b/db/migrate/20161202152031_remove_duplicates_from_routes.rb
index 510796e05f26e7040d359d47a78314c626cafb1d..a21bde699951950f3b18551a4e9714ee08ce0ed2 100644
--- a/db/migrate/20161202152031_remove_duplicates_from_routes.rb
+++ b/db/migrate/20161202152031_remove_duplicates_from_routes.rb
@@ -7,6 +7,11 @@ class RemoveDuplicatesFromRoutes < ActiveRecord::Migration
   DOWNTIME = false
 
   def up
+    # We can skip this migration when running a PostgreSQL database because
+    # we use an optimized query in the "FillProjectsRoutesTable" migration
+    # to fill these values that avoid duplicate entries in the routes table.
+    return unless Gitlab::Database.mysql?
+
     select_all("SELECT path FROM #{quote_table_name(:routes)} GROUP BY path HAVING COUNT(*) > 1").each do |row|
       path = connection.quote(row['path'])
       execute(%Q{