0
0
SQLquery~5 mins

Why understanding relationships matters in SQL

Choose your learning style9 modes available
Introduction

Understanding relationships helps you connect data from different tables. This makes your data useful and meaningful.

You want to find all orders made by a specific customer.
You need to see which products belong to which category.
You want to combine employee details with their department information.
You want to track which students are enrolled in which classes.
Syntax
SQL
SELECT columns FROM table1
JOIN table2 ON table1.common_column = table2.common_column;
Use JOIN to connect tables based on a shared column.
The common column usually holds related information like IDs.
Examples
This query shows customer names with their order IDs by linking Customers and Orders tables.
SQL
SELECT Customers.Name, Orders.OrderID
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
This query connects employees to their departments using the DepartmentID.
SQL
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
Sample Program

This example creates two tables, Customers and Orders, inserts data, and then shows which products each customer bought by joining on CustomerID.

SQL
CREATE TABLE Customers (
  CustomerID INT PRIMARY KEY,
  Name VARCHAR(50)
);

CREATE TABLE Orders (
  OrderID INT PRIMARY KEY,
  CustomerID INT,
  Product VARCHAR(50)
);

INSERT INTO Customers VALUES (1, 'Alice'), (2, 'Bob');
INSERT INTO Orders VALUES (101, 1, 'Book'), (102, 2, 'Pen'), (103, 1, 'Notebook');

SELECT Customers.Name, Orders.Product
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.Name;
OutputSuccess
Important Notes

Relationships let you avoid repeating data in many tables.

Always use the correct columns to join tables to get accurate results.

Summary

Relationships connect data across tables.

JOINs use common columns to link tables.

Understanding relationships helps answer real questions from data.