Solution: Divide and Conquer

Let's learn to solve the Spaghetti Query antipattern by using the divide and conquer approach.

A famous quote by William of OckhamEnita non sunt multiplicanda praeter necessitatem (Latin, “Entities are not to be multiplied beyond necessity.”). also known as the law of parsimony, goes as follows:

The Law of Parsimony

This law essentially states that: “When you have two competing theories that make exactly the same predictions, the simpler one is the better.”

What this means in SQL is that when we have a choice between two queries that produce the same result set, we should choose the simpler one. We should keep this in mind when straightening out instances of this antipattern.

One step at a time

When we can’t find a logical JOIN condition between the tables involved in an unintended Cartesian product, it could be because there simply is no such condition. To avoid the Cartesian product, we have to split up a Spaghetti Query into several simpler queries. In the simple example shown earlier, we need only two queries. The query to retrieve count_fixed is written in the following playground.

Get hands-on with 1200+ tech skills courses.