Logo hdtoledo
hdtoledo.dev
Módulos_del_Sistema
MÓDULO_TEÓRICO

Cash Register Close (Grouping)

Cash Register Close and Grouping

Cash Register Close (Grouping)

It's 10:00 PM and Doña Pepa is closing the mini-market. She pulls out her cash register filled with 500 individual receipts. She doesn't want to read receipt by receipt; she wants to answer key questions for her business:

  1. How much total money came in today?
  2. How many milks did I sell compared to breads?

For the database to answer this in a microsecond, we use Aggregation Functions and the powerful GROUP BY command.


Quick Math (Aggregation Functions)

SQL comes with a built-in calculator. Instead of returning the rows to us, we can ask it to do math with them.

  • COUNT(): "Count how many records there are."
  • SUM(): "Add up all the numbers in this column."
  • AVG(): "Calculate the average."

If Pepa wants to know the total money for the day, she would use a JOIN with a SUM:

sql
SELECT SUM(Products.price) AS total_money_today FROM Sales INNER JOIN Products ON Sales.id_product = Products.id_product;

Result: A single row that says "total_money_today: $154.50".


Separating into Little Piles (GROUP BY)

But the true power comes when Pepa wants to know which product sold the most.

To do this in real life, Pepa would have to separate the receipts into "little piles":

  1. A little pile for all the Milk receipts.
  2. A little pile for all the Bread receipts.
  3. Then, she counts each little pile separately.

In SQL, "separating into little piles" is called GROUP BY.

sql
SELECT Products.name AS product, COUNT(Sales.id_sale) AS amount_sold FROM Sales INNER JOIN Products ON Sales.id_product = Products.id_product GROUP BY Products.name;

What is the machine doing here?

  1. It gathers all the sales with their products (The INNER JOIN).
  2. It looks at the GROUP BY Products.name instruction and groups everything that says "Milk" into one "little pile," and everything that says "Bread" into another.
  3. Finally, it applies the math calculator (COUNT) to each little pile, counting them one by one.

Result:

  • Milk: 45 sold.
  • Bread: 120 sold.

Pepa just did her cash register close for the entire day (or the entire year) in less than 1 second! With this information, she can decide to buy more bread tomorrow.

In the next lesson, we will see how to make these mathematical searches ultra-fast even if Pepa had 1 million customers, thanks to the magic of Indexes.