diff --git a/app/models/ci/build.rb b/app/models/ci/build.rb
index 79f040b8954be0a54fbf0d828f5c5f6b0212ae0b..30a8b5aa816278b66dfc39937f95ab3a4c9eb4a1 100644
--- a/app/models/ci/build.rb
+++ b/app/models/ci/build.rb
@@ -47,7 +47,7 @@ module Ci
     scope :failed, ->() { where(status: "failed")  }
     scope :unstarted, ->() { where(runner_id: nil) }
     scope :running_or_pending, ->() { where(status:[:running, :pending]) }
-    scope :latest, ->() { group(:name).order(stage_idx: :asc, created_at: :desc) }
+    scope :latest, ->() { where(id: unscope(:select).select('max(id)').group(:name)).order(stage_idx: :asc) }
     scope :ignore_failures, ->() { where(allow_failure: false) }
     scope :for_ref, ->(ref) { where(ref: ref) }
 
diff --git a/app/models/ci/commit.rb b/app/models/ci/commit.rb
index 59d4932d43402b8c10fee1fa2d9674d9d120d320..31da7e8f2b6fc09342b5b2e994db892fa822e941 100644
--- a/app/models/ci/commit.rb
+++ b/app/models/ci/commit.rb
@@ -114,14 +114,11 @@ module Ci
     end
 
     def builds_without_retry
-      @builds_without_retry ||=
-        begin
-          grouped_builds = builds.group_by(&:name)
-          latest_builds = grouped_builds.map do |name, builds|
-            builds.sort_by(&:id).last
-          end
-          latest_builds.sort_by(&:stage_idx)
-        end
+      builds.latest
+    end
+
+    def builds_without_retry_for_ref(ref)
+      builds.for_ref(ref).latest
     end
 
     def retried_builds
@@ -181,7 +178,7 @@ module Ci
     end
 
     def duration_for_ref(ref)
-      builds_without_retry.for_ref(ref).select(&:duration).sum(&:duration).to_i
+      builds_without_retry_for_ref(ref).select(&:duration).sum(&:duration).to_i
     end
 
     def finished_at
@@ -198,7 +195,7 @@ module Ci
     end
 
     def matrix_for_ref?(ref)
-      builds_without_retry.for_ref(ref).pluck(:id).size > 1
+      builds_without_retry_for_ref(ref).pluck(:id).size > 1
     end
 
     def config_processor
diff --git a/app/views/ci/builds/show.html.haml b/app/views/ci/builds/show.html.haml
index e4ec190ada5bcd14ce5a72bca877b4d6b48edb6a..c42d11bf05deaa85d25ca212126f5815ef0f84e8 100644
--- a/app/views/ci/builds/show.html.haml
+++ b/app/views/ci/builds/show.html.haml
@@ -1,7 +1,7 @@
 #up-build-trace
 - if @commit.matrix_for_ref?(@build.ref)
   %ul.center-top-menu
-    - @commit.builds_without_retry.for_ref(build.ref).each do |build|
+    - @commit.builds_without_retry_for_ref(build.ref).each do |build|
       %li{class: ('active' if build == @build) }
         = link_to ci_project_build_url(@project, build) do
           = ci_icon_for_status(build.status)
@@ -12,7 +12,7 @@
               = build.id
 
 
-    - unless @commit.builds_without_retry.for_ref(@build.ref).include?(@build)
+    - unless @commit.builds_without_retry_for_ref(@build.ref).include?(@build)
       %li.active
         %a
           Build ##{@build.id}