Skip to main content

How can I improve query time in SQL ? (PostgreSQL)

Databases • Asked by Boris Bresciani


I have 4 models:

class Match < ApplicationRecord
  belongs_to :tournament
  scope :next, -> { where('date > ?', }
class Tournament < ApplicationRecord
  belongs_to :region
  has_many :matches, dependent: :destroy
class Region < ApplicationRecord
  belongs_to :sport
  has_many :tournaments, dependent: :destroy
  has_many :matches, through: :tournaments
class Sport < ApplicationRecord
  has_many :regions, dependent: :destroy
  has_many :matches, through: :regions

I'm looking for the number of matches in the future from Sport, so actually i do this:

But my problem is that sometimes it's very long to look for it especially when I have a lot of data (well it's normal) but I'm trying to optimize)

Thank you for your help !


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.