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.salesFROM Orders AS
OINNER 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 tableP.product_name
→ product name from the Products tableO.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 writingOrders.product_id
every time, we can just writeO.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 aliasP
, so we can referenceProducts.product_name
simply asP.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
) equalsproduct_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.salesFROM
OrdersINNER 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.