r/learnSQL • • Jan 10 '26

SQL performance improvement training question

  1. The following query compute pairs of comedies by the same director:

# Movies pairs of the same director

Select

d.first_name

, d.last_name

, fm.name

, sm.name

from

movies_genres as fmg

join

movies as fm

on

fmg.movie_id = fm.id

join

imdb_ijs.movies_directors as fmd

on

fm.id = fmd.movie_id

join

imdb_ijs.movies_directors as smd

on

fmd.director_id = smd.director_id

join

imdb_ijs.movies as sm

on

smd.movie_id = sm.id

join

imdb_ijs.directors as d

on

fmd.director_id = d.id

join

movies_genres as smg

on

sm.id = smg.movie_id

where

fmd.movie_id != smd.movie_id # Avoid reflexiveness

and

fmd.movie_id > smd.movie_id # No symmetry

and

fmg.genre = 'Comedy'

and

smg.genre = 'Comedy'

order by

d.first_name, d.last_name, fm.name, sm.name

;

There is a lot that can be done to improve the query performance.

  1. Compute the execution plan and time of the original query.
  2. Try to improve the query in steps. Per step:
    1. Explain the intuition explaining why it should improve the performance.
    2. Implement the change.
    3. Compute the execution plan and time of the new query.
    4. Steps that do not improve are also good. Trial and error is very common in this field. Explain why these steps did not improve.
5 Upvotes

16 comments sorted by

View all comments

Show parent comment

1

u/idan_huji Jan 13 '26

Sure, I read that and I agree.
The condition left in the from is still too late.

Actually, since comedies are used on both sides, extracting them first (e.g., auxiliary table), should improve the performance.