Crossing Information (JOINS)

Crossing Information (JOINS)
In the previous lesson, we saw how the "Marie Kondo Method" (Normalization) separated everything into clean, tidy drawers.
But we have a small problem: When Juan (Customer 1) goes to pay for his Milk (Product 2), Doña Pepa can't print him a receipt that says: "Customer ID 1 bought Product ID 2". Juan would be very confused.
The receipt must say: "Juan García bought Milk".
To achieve this, we need to build temporary bridges that link the separated information just for the moment we want to read it. We call these bridges JOINS.
The Perfect Fusion: INNER JOIN
The INNER JOIN is the magic glue. We tell the database: "Bring the information from the Sales table, and join it with the Customers table, BUT only connect the pieces where the ID matches".
sqlSELECT Sales.id_sale, Customers.name AS customer, Products.name AS product FROM Sales INNER JOIN Customers ON Sales.id_customer = Customers.id_customer INNER JOIN Products ON Sales.id_product = Products.id_product;
Anatomy of the code:
SELECT: We choose exactly which columns we want to print on the receipt. We useASto give them a nicer nickname.FROM Sales: Our main table, where it all started.INNER JOIN Customers: "Bring the Customers table..."ON ...: "...and join them exactly WHERE the customer's ID in the sale matches the customer's ID in their table". This is the condition that makes the bridge fit perfectly!
The result will be a beautiful, easy-to-read table for Doña Pepa, combining the three entities into a single view.
What if information is missing? (LEFT JOIN)
The INNER JOIN is strict: it only shows results if there is information on both sides of the bridge. If a customer has never bought anything, the INNER JOIN ignores them completely.
But what if Doña Pepa wants a list of ALL her registered customers, regardless of whether they have bought something or not, to send them a promotional WhatsApp message?
For that we use the LEFT JOIN (Join by the left).
sqlSELECT Customers.name, Sales.id_sale FROM Customers LEFT JOIN Sales ON Customers.id_customer = Sales.id_customer;
The LEFT JOIN says: "Bring me absolutely EVERYTHING from the left table (Customers). If they have sales on the right, show them. If they don't have sales, put an empty space (NULL)".
With this intersection, Doña Pepa will see Juan with his Milk sale, but she will also see Doña María with a big NULL (empty) next to her, indicating that María hasn't bought anything yet.
Now the cash register is capable of crossing data like a pro! In the next lesson, we will see how Doña Pepa can do her cash register close at the end of the day by summing up all the money using Grouping (GROUP BY).
