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.
6 Upvotes

16 comments sorted by

View all comments

Show parent comment

1

u/idan_huji Jan 12 '26

This is a too good answer, I'm afraid that my students will find it.
By the way, why do you put one comedy condition in the on and the other in the where?

1

u/r3pr0b8 Jan 12 '26

why do you put one comedy condition in the on and the other in the where?

comedy ?? LOL

i mentioned why in my post --

conditions on the first table mentioned in the FROM clause can go in the WHERE clause, all other conditions should be moved to their ON clauses for clarity (and note especially the effect in LEFT OUTER joins)

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.