Conceptual
Login

Let the Database Do the Arithmetic Instead of Looping in Your Code

A dashboard that shows a total per customer can be written two ways: pull every order row into the application and add them up in a loop, or send one GROUP BY query and read back one row per customer. The second is almost always faster, because the sum happens next to the data instead of after a million rows cross the network, and an index can often feed the grouping directly. The rule of thumb: move the filtering and the arithmetic to the side that holds the rows, and return only what the screen will show.

Questions this Concept answers

  • Why is one `GROUP BY` usually far faster than summing rows in application code?