Antipattern: Solve a Complex Problem in One Step

Let's look into the drawbacks of retrieving results in one go in detail.

SQL is a very expressive language — you can accomplish a lot in a single query or statement. But that doesn’t mean it’s mandatory or even a good idea to aim to solve every problem in one line of code. Do we have this habit with any other programming language we use? Probably not.

Unintended products

One common consequence of producing all our results in one query is something called a Cartesian product. This happens when two of the tables in the query have no condition restricting their relationship. Without such a restriction, the JOIN for the two tables pairs each row in the first table to every row in the other table. Each such pairing becomes a row of the result set, and we end up with many more rows than we expected.

Let’s see an example. Suppose we want to query our bugs database to count the number of bugs, fixed and open, for a given product. Many programmers would try to use a query like the following to calculate these counts:

Get hands-on with 1200+ tech skills courses.