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?
The Hidden Costs of ORMs: When Raw SQL Is the Better Choice
This explains what happens when your program pulls thousands of database rows into memory and adds them up in a loop, instead of asking the database for the total directly. The database can do the su…