0

I have been using the Django Rest Framework, and part of the ORM does the following query as part of a generic object list endpoint:

`SELECT COUNT(*) AS `__count`
FROM `album`
INNER JOIN `tracks`
    ON (`album`.`id` = `tracks`.`album_id`)
WHERE `tracks`.`viewable` = 1`

The API is supposed to only display albums with tracks that are set to viewable, but with a tracks table containing 50 million rows this is query never seem to complete and hangs the endpoint's execution.

All columns referenced are indexed, so I do not know why this is taking so long to execute. If there are any potential optimisations that I might have not considered please let me know.

3
  • So there are indices on the album_id and viewable columns in the tracks table? Other than this, I don't see any possible optimizations. You could also run EXPLAIN on this query to see what is going on. Commented Mar 16, 2018 at 1:43
  • That is correct. :/ I guess I'll have to see if there's a way to override how Django determines it's count, because this query is generated automatically. The EXPLAIN resulted in >20 million rows being selected so I guess it's no wonder that the join is going to take some time... Commented Mar 16, 2018 at 2:32
  • 50 million rows is a lot of data. If you need the results of this query often, perhaps you can cache it somewhere. Commented Mar 16, 2018 at 2:34

1 Answer 1

2

For this query:

SELECT COUNT(*) AS `__count`
FROM `album` INNER JOIN 
     `tracks`
     ON (`album`.`id` = `tracks`.`album_id`)
WHERE `tracks`.`viewable` = 1`;

An index on tracks(viewable, album_id) and album(id) would help.

But, in all likelihood a join is not needed, so you can do:

select count(*)
from tracks
where viewable = 1;

For this the index on tracks(viewable) will be a big help.

Sign up to request clarification or add additional context in comments.

2 Comments

Assuming id is the primary key of album, I think it should already be indexed. +1 for your second query suggestion.
Thanks, I already have indexes on all mentioned columns though... and my overall goal is to obtain the album records based on the track relation having viewable set to 1, not the tracks themselves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.