Improve Slow Query

created:

updated:

tags: database query

Today I’d like to write about what I learned from coworkers sharing their knowledge on how they improved slow query.

The method that improved the slow query was to invert the Django ORM by using De Morgan’s Law but which avoids unnecessary LEFT/RIGHT JOIN that will make the size of the query very large.

De Morgan’s Law

not(A or B) == (not A) and (not B)

We used this law to improve the slow query.

How De Morgan’s Law helped improve slow query

Although both not (A or B) and (not A) and (not B) are equivalent, the actual database SQL can be vastly different. For instance, not (A or B) may produce lots of LEFT/RIGHT JOIN that may increase the size of the query, whereas the other may be much more efficient SQL.

Other methods to improve SQL query

Inverting database ORM logic can be definitely a good trick to improve slow query.

Nevertheless, senior members from our team advised that the best way is to observe the actual SQL query produced and find the actual slow part of that query and improve it. This will require the knowledge of SQL query.

References