SQL for Beginners: How to Do Joins

When you work with databases, data is often split across multiple tables. For example:

  • One table (Orders) stores order details like product IDs and sales.
  • Another table (Products) stores product names and descriptions.

If you want to combine them, you use a JOIN. Let’s walk through an example together.


1. Example Query

SELECT
O.product_id,
P.product_name,
O.sales
FROM Orders AS O
INNER JOIN Products AS P
ON O.product_id = P.product_id;


2. Breaking It Down

🔹 SELECT

Tells SQL which columns you want in the result.

SELECT O.product_id, P.product_name, O.sales

Here we’re asking for:

  • O.product_id → product ID from the Orders table
  • P.product_name → product name from the Products table
  • O.sales → sales value from the Orders table

🔹FROM Orders AS O

This is the starting table.

  • Orders is the name of the table.
  • AS O creates an alias (a shortcut name). Instead of writing Orders.product_id every time, we can just write O.product_id.

👉 Aliases make code cleaner and easier to read, especially when working with multiple tables.


🔹 INNER JOIN Products AS P

This tells SQL we want to combine the Orders table with the Products table.

  • Products is the second table.
  • AS P gives it the alias P, so we can reference Products.product_name simply as P.product_name.

🔹ON O.product_id = P.product_id

This is the join condition.
It tells SQL how the two tables are related:

  • Match rows where product_id in Orders (O.product_id) equals product_id in Products (P.product_id).

If a product ID appears in both tables, it shows up in the result. If it doesn’t exist in one table, it’s excluded (because this is an INNER JOIN).


3. What the Query Produces?

After running the query, the database combines the tables and produces something like this:

Now, instead of just seeing numbers (IDs), you also see the product names linked to those orders.


4. Why Aliases Matter (AS)

Without aliases, the query would look like this:

SELECT Orders.product_id, Products.product_name, Orders.sales
FROM Orders
INNER JOIN Products
ON Orders.product_id = Products.product_id;

This works — but it’s longer and harder to read.
By using aliases (AS O, AS P), we make the query shorter, cleaner, and easier to maintain.


5. Key Takeaways

  • SELECT → Choose the columns you want.
  • FROM → Start with your first table.
  • AS (alias) → Create a shortcut name for a table.
  • INNER JOIN → Combine tables where there’s a match.
  • ON → Define the relationship between the tables.
Author:
Zainul Abedin Natha
Powered by The Information Lab
1st Floor, 25 Watling Street, London, EC4M 9BR
Subscribe
to our Newsletter
Get the lastest news about The Data School and application tips
Subscribe now
© 2025 The Information Lab