Skip to content
Advertisement

How to improve SQL query performance for HAVING (SQLite)

These 2 queriess are taking several minutes on tables of several millions rows (2 tables: torrents and dates). None of the columns are indexed I believe. I don’t know SQL well. Is there any way to make them faster?

Here are the queries:

// torrents with no dates yet (116278ms)
  SELECT
    torrents.*
  FROM
    torrents
  LEFT JOIN 
    dates ON dates.infohash = torrents.infohash
  GROUP BY
      torrents.infohash
  HAVING 
     COUNT(dates.date) = 0

// yesterday high stats torrents (348024ms)
  SELECT
    torrents.*
  FROM
    torrents
  LEFT JOIN 
    dates ON dates.infohash = torrents.infohash
  GROUP BY
    dates.dateInfohash
  HAVING
    dates.date = '2019-09-10'
  ORDER BY 
    peers DESC
  LIMIT 5000

Advertisement

Answer

You don’t need the GROUP BY or HAVING clauses

// torrents with no dates yet
      SELECT torrents.*
      FROM torrents
       LEFT JOIN dates ON dates.infohash = torrents.infohash
       WHERE dates.date IS NULL

// yesterday high stats torrents
      SELECT torrents.*
     FROM torrents
     LEFT JOIN dates ON dates.infohash = torrents.infohash
     WHERE dates.date = '2019-09-10'
     ORDER BY peers DESC
     LIMIT 5000

The first one probably doesn’t even need the WHERE dates.date IS NULL since I assume that there’s no record in the dates table without a date. UPDATE: But then you would need to change the LEFT JOIN to INNER JOIN.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement