joins in mysql
š What Are JOINS?
JOINS allow you to combine data from two or more tables based on a related column.
Think of it as building relationships between tables in a relational database to retrieve meaningful combined data.
š§ Key Concepts:
Relational databases store related data across multiple tables.
JOINS use common fields (like
emp_no) to connect rows that are logically related.You can retrieve columns from multiple tables in a single query.
šļø Example Tables:
employeesā hasemp_no,first_name,last_namedept_empā hasemp_no,dept_no,from_date
You can JOIN them using emp_no to get:
Employee number
Name
Department number
Start date of their department role
ā ļø Important Notes:
The columns used to join must be of the same type and refer to the same concept (e.g., employee ID).
Tables donāt have to be logically adjacent in the schema ā you can JOIN any tables as long as thereās a related field.
š§° Coming Up:
Next lecture covers
INNER JOINsyntax and behavior.You'll also get to practice JOINs using duplicate tables youāll create (
departments_dup,dept_manager_dup).
task:If you currently have the ādepartments_dupā table set up, use DROP COLUMN to remove the ādept_managerā column from the ādepartments_dupā table.
Then, use CHANGE COLUMN to change the ādept_noā and ādept_nameā columns to NULL.
(If you donāt currently have the ādepartments_dupā table set up, create it. Let it contain two columns: dept_no and dept_name. Let the data type of dept_no be CHAR of 4, and the data type of dept_name be VARCHAR of 40. Both columns are allowed to have null values. Finally, insert the information contained in ādepartmentsā into ādepartments_dupā.)
Then, insert a record whose department name is āPublic Relationsā.
Delete the record(s) related to department number two.
Insert two new records in the ādepartments_dupā table. Let their values in the ādept_noā column be ād010ā and ād011ā.
# if you currently have ādepartments_dupā set up:
ALTER TABLE departments_dup
DROP COLUMN dept_manager;
ALTER TABLE departments_dup
CHANGE COLUMN dept_no dept_no CHAR(4) NULL;
ALTER TABLE departments_dup
CHANGE COLUMN dept_name dept_name VARCHAR(40) NULL;
# if you donāt currently have ādepartments_dupā set up
DROP TABLE IF EXISTS departments_dup;
CREATE TABLE departments_dup
(
dept_no CHAR(4) NULL,
dept_name VARCHAR(40) NULL
);
INSERT INTO departments_dup
(
dept_no,
dept_name
)SELECT
*
FROM
departments;
INSERT INTO departments_dup (dept_name)
VALUES ('Public Relations');
DELETE FROM departments_dup
WHERE
dept_no = 'd002';
INSERT INTO departments_dup(dept_no) VALUES ('d010'), ('d011');
š INNER JOIN: The Basics
An INNER JOIN returns only matching records from both tables based on a common column.
Think of it as the overlap in a Venn diagram.
š§ When to Use INNER JOIN
When you want rows that exist in both tables based on a shared key.
Non-matching rows (i.e., nulls or unmatched values) are excluded from the result.
šļø Example Tables Used:
dept_manager_dup(left table)departments_dup(right table)Join column:
dept_no(department number)
š¹ INNER JOIN Syntax:
SELECT t1.column1, t2.column2, ...
FROM dept_manager_dup t1
JOIN departments_dup t2
ON t1.dept_no = t2.dept_no;
t1andt2are table aliases to simplify your code.ON t1.dept_no = t2.dept_notells SQL how to match rows.
ā Best Practices:
Always qualify column names with their table alias (
t1.column,t2.column) to avoid confusion.Use aliases to keep queries readableāespecially with multiple JOINs.
š Recap of Tablesā Data:
- Some records in both tables lack department numbers or have null values ā These will not appear in INNER JOIN results.
š“ Summary of INNER JOIN Behavior:
| Match Exists | Included in Result? |
| ā Yes | ā Yes |
| ā No | ā No |
š§¾ Goal of the Query:
Extract a list of:
dept_no(Department Number)emp_no(Employee Number)dept_name(Department Name)
From:
dept_manager_dup(aliased as M)departments_dup(aliased as D)
ā INNER JOIN Query Used:
SELECT M.dept_no, M.emp_no, D.dept_name
FROM dept_manager_dup M
INNER JOIN departments_dup D
ON M.dept_no = D.dept_no
ORDER BY M.dept_no;
š What This Query Does:
Matches records from both tables where
dept_novalues are the sameRetrieves only rows where this match exists
Excludes:
Any rows with NULL values in
dept_noDepartments that exist in one table but not the other
š§ Key Points from the Analysis:
INNER JOIN acts like the overlap in a Venn diagram
It excludes NULLs and non-matching values
In this example:
Departments 1, 2, 10, and 11 were missing in the final output
NULL department numbers were also excluded
Final result showed only matching department numbers (3ā9) ā 20 rows total
š Reminder:
INNER JOIN = "Show me only what both tables have in common"
task:Extract a list containing information about all managersā employee number, first and last name, department number, and hire date.
SELECT
e.emp_no,
e.first_name,
e.last_name,
dm.dept_no,
e.hire_date
FROM
employees e
JOIN
dept_manager dm ON e.emp_no = dm.emp_no;
š§ Key Notes on Using JOINs (Not Just INNER JOINs):
ā 1. Select Any Columns You Want
You can select any combination of columns from the joined tables.
Just make sure the column is from one of the tables involved in the JOIN.
Example (adding contract dates):
SELECT M.dept_no, M.emp_no, D.dept_name, M.from_date, M.to_date
FROM dept_manager_dup M
JOIN departments_dup D
ON M.dept_no = D.dept_no;
ā 2. Table Aliases Can Be Declared Early
Some people start with the
FROMandJOINsection to define aliases early.This can help with readabilityāespecially when joining multiple tables.
Example:
FROM dept_manager_dup M
JOIN departments_dup D
ON M.dept_no = D.dept_no
Then use M and D in the SELECT clause.
ā
3. INNER Keyword is Optional
JOIN=INNER JOINby default.Practitioners often omit the word
INNERto write cleaner code.
JOIN departments_dup D -- Same as INNER JOIN
ā 4. Matching Column Order Doesnāt Matter
M.dept_no = D.dept_no
-- is the same as --
D.dept_no = M.dept_no
Itās just about your preference and readability.
ā
5. Be Careful with ORDER BY in Larger Queries
- If two tables share the same column name (e.g.,
dept_no), it's better to specify the table alias:
ORDER BY M.dept_no
- This becomes crucial in larger datasets and with tools like procedures or indexes.
š” Final Tip:
Always write clear, readable JOINs, especially as you work with more complex databases.
š What Are Duplicate Records?
Duplicate rows = rows where all column values are identical.
Common in raw or uncontrolled data.
Best practice is to avoid or clean them, but sometimes they exist.
š§Ŗ Example in Practice:
Two duplicates were manually added:
A duplicate manager row with
emp_no = 110228,dept_no = 3A duplicate department entry for
dept_no = 9(Customer Service)
šÆ Effect on JOIN Output:
Before duplicates: 20 rows
After duplicates: 25 rows
Why the increase?
One duplicate manager ā +1 row
One duplicate department ā causes each related employee to match twice, adding +4 rows
ā How to Handle Duplicates in Query Results:
Use GROUP BY:
SELECT M.emp_no, D.dept_name
FROM dept_manager_dup M
JOIN departments_dup D ON M.dept_no = D.dept_no
GROUP BY M.emp_no;
Why
GROUP BY M.emp_no?Because
emp_nois the field that differs most and uniquely identifies managers.This removes the effect of duplicated rows by collapsing results per unique employee.
š§ Best Practice Reminder:
Never assume your data is cleanāespecially with large datasets.
Use
GROUP BYproactively when duplicate outputs are not desirable.
š What Is a LEFT JOIN?
A LEFT JOIN returns:
All matching rows from both tables (just like
INNER JOIN)Plus all unmatched rows from the left table, with
NULLvalues for missing matches on the right
šµ Think of a Venn diagram:
The red area = what INNER JOIN shows (the overlap)
The blue area = the rest of the left table ā only LEFT JOIN includes this
š Example Setup:
Tables used:
dept_manager_dup(aliased asM)departments_dup(aliased asD)
Related by:
dept_no
ā LEFT JOIN Syntax:
SELECT M.dept_no, M.emp_no, D.dept_name
FROM dept_manager_dup M
LEFT JOIN departments_dup D
ON M.dept_no = D.dept_no;
š§Ŗ Result Analysis:
INNER JOIN returned 20 rows
LEFT JOIN returned 26 rows ā 6 additional non-matching rows from the left table
The 6 extra rows include:
4 records from
Mwithdept_novalues that donāt exist inD- These show
NULLin thedept_namefield
- These show
2 records with
dept_no = 2fromM, but no match inD- These also show
NULLfordept_name
- These also show
ā ļø Important Reminder:
LEFT JOIN is directional. The table on the left determines what "non-matching" rows get included.
Switching M and D in the join will change the result!
š¬ In Simple Terms:
INNER JOIN ā only what matches
LEFT JOIN ā all from the left, matches from the right, and
NULLif no match
task:Join the 'employees' and the 'dept_manager' tables to return a subset of all the employees whose last name is Markovitch. See if the output contains a manager with that name.
Hint: Create an output containing information corresponding to the following fields: āemp_noā, āfirst_nameā, ālast_nameā, ādept_noā, āfrom_dateā. Order by 'dept_no' descending, and then by 'emp_no'.
SELECT
e.emp_no,
e.first_name,
e.last_name,
dm.dept_no,
dm.from_date
FROM
employees e
LEFT JOIN
dept_manager dm ON e.emp_no = dm.emp_no
WHERE
e.last_name = 'Markovitch'
ORDER BY dm.dept_no DESC, e.emp_no;
