Sub topic 1
What a Join Does
A relational database splits data across tables so that each fact is stored once. An employee row holds a department_id, and the department's name lives in the departments table. A join recombines those tables at query time. This chapter gives the model you need for the rest of the tutorial: what a join produces, how the join condition decides which rows pair up, and which rows are lost along the way.
Prerequisites
This chapter assumes you can already do the following:
- Write a basic
SELECTwithWHEREandORDER BY. - Explain what a primary key and a foreign key are.
- Give a table an alias, as in
FROM employees e. - Describe how
NULLbehaves: it is "unknown", soNULL = NULLis not true.
The examples use two sources of data. The first is Oracle's sample HR schema, which provides employees and departments. The second is a few small tables you can create yourself, so you can see every row. Both work in SQL*Plus, SQLcl, SQL Developer or any other Oracle client.
The Model: Pair Rows, Then Keep the Matches
A join takes two row sources and produces one. Conceptually it works in two steps:
- Form every possible pairing of a row from the first source with a row from the second. This is the Cartesian product. With 3 rows on one side and 4 on the other, there are 12 pairs.
- Keep only the pairs for which the join condition is true.
The optimizer never builds the full product for a normal join. It uses hash joins, nested loops, indexes and similar methods. But the result always has to match this two-step definition. Keeping it in mind explains most surprises later, including duplicate rows, missing rows and slow queries.
The branch labelled "no, or unknown" matters. A condition that evaluates to NULL is treated like false, and the pair is discarded.
A Small Dataset
Run this script to create tables small enough to check by eye.
CREATE TABLE dept_demo (
dept_id NUMBER PRIMARY KEY,
dept_name VARCHAR2(30) NOT NULL
);
CREATE TABLE emp_demo (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(30) NOT NULL,
dept_id NUMBER REFERENCES dept_demo (dept_id)
);
INSERT INTO dept_demo VALUES (10, 'Sales');
INSERT INTO dept_demo VALUES (20, 'IT');
INSERT INTO dept_demo VALUES (30, 'Legal');
INSERT INTO emp_demo VALUES (1, 'Ana', 10);
INSERT INTO emp_demo VALUES (2, 'Ben', 10);
INSERT INTO emp_demo VALUES (3, 'Chen', 20);
INSERT INTO emp_demo VALUES (4, 'Dara', NULL);
COMMIT;The data has two deliberate features:
- Legal has no employees.
- Dara has no department. Her
dept_idisNULL, which the foreign key allows.
Every join variant in this tutorial behaves differently on those two rows, so keep them in mind.
Your First Join
The most common join is the inner join. It keeps only the pairs where the condition is true.
SELECT e.emp_name, d.dept_name
FROM emp_demo e
INNER JOIN dept_demo d
ON e.dept_id = d.dept_id
ORDER BY e.emp_name;The result has three rows:
| EMP_NAME | DEPT_NAME |
|---|---|
| Ana | Sales |
| Ben | Sales |
| Chen | IT |
Here is how the model explains this output. There are 4 employees and 3 departments, so 12 pairs are formed. Only 3 pairs have equal dept_id values. Dara's pair with each department compares NULL to a number, which is unknown, so all of her pairs are discarded. Legal matches no employee, so it never appears.
Dara and Legal are not an error. An inner join answers the question "which employees have a department, and what is it?" and nothing more. When you need to keep unmatched rows, you use an outer join, which a later chapter covers.
Two Syntaxes for the Same Join
Oracle accepts two ways of writing a join. Both produce the same inner join here.
The ANSI syntax names the join type and puts the condition in an ON clause:
SELECT e.employee_id, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;The older comma syntax lists the tables in FROM and puts the condition in WHERE:
SELECT e.employee_id, e.last_name, d.department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id;For inner joins the two forms are equivalent, and Oracle's optimizer treats them identically. Which one to use is a style choice with some practical consequences:
| Aspect | ANSI (`JOIN ... ON`) | Comma syntax |
|---|---|---|
| Where the join condition goes | `ON` clause | `WHERE` clause |
| Where row filters go | `WHERE` clause | `WHERE`, mixed with join conditions |
| Outer joins | `LEFT`, `RIGHT`, `FULL OUTER JOIN` | `(+)` operator, with restrictions |
| Forgetting a condition | Syntax error for `INNER JOIN` without `ON` | Silently produces a Cartesian product |
| Standard | SQL standard, portable | Oracle-era legacy style, still valid |
The last row of the table is a practical concern. If you write FROM employees e, departments d and forget the WHERE condition, Oracle runs the query and returns every pairing. INNER JOIN without ON is rejected, so the mistake is caught immediately.
You will meet both styles in real codebases. Much existing Oracle code was written before Oracle 9i added ANSI joins, so this tutorial teaches you to read the older form and write the newer one.
What Makes a Join Condition
The join condition is an ordinary boolean expression. Most often it is an equality between a foreign key and the primary key it references:
ON e.dept_id = d.dept_idThis is called an equi-join. Other comparison operators are allowed, and they produce non-equi joins, which a later chapter covers. A condition can also combine several tests with AND, which is useful for composite keys.
Two rules apply to every condition:
- Qualify shared column names. If both tables have a column called
dept_id, writingdept_idalone raisesORA-00918: column ambiguously defined. Prefix it with the table alias, as ine.dept_id. - Use the alias once you define it. After you write
FROM emp_demo e, you cannot refer to the table asemp_demo.dept_idin the same query. Oracle reportsORA-00904: invalid identifier.
Seeing the Row Multiplication
The "pair everything, then filter" model predicts something that surprises beginners: a join can return more rows than either table holds. Each row on one side pairs with every matching row on the other.
Suppose the department table had two rows for dept 10 by mistake. Ana and Ben would each match both, and the join would return four rows for them instead of two. The query would still run without errors. The joined result has one row per matching pair, not one row per employee.
You can check for this by comparing counts. Count the rows of the driving table, then count the joined result:
SELECT COUNT(*) AS employees_total
FROM emp_demo;
SELECT COUNT(*) AS joined_rows
FROM emp_demo e
JOIN dept_demo d ON e.dept_id = d.dept_id;The first query returns 4 and the second returns 3. The difference of one is Dara, who was discarded because her key is NULL. If the joined count were higher than the table count, some key would be repeated on the other side.
When the joined side's join column is a primary key or has a unique constraint, each employee matches at most one department. In that case the joined result cannot have more rows than emp_demo. A later chapter on pitfalls returns to this check.
What a Join Does Not Do
Keep these limits in mind:
- It does not modify the tables. A join is part of a query. It builds a temporary result and changes no stored data.
- It does not guarantee order. Without
ORDER BY, the row order of a join result is not defined, even if it looks stable on your test data. - It does not enforce relationships. Joining on
dept_idworks whether or not a foreign key exists. The constraint protects the data. The join only reads it. Joining on columns that are unrelated in meaning gives results that run but are wrong.
The Road Ahead
The rest of the tutorial builds on this model. Each topic changes one part of it:
- Outer joins keep pairs the condition rejects, by adding a row of
NULLs for the unmatched side. - Where you write a filter (
ONorWHERE) changes whether those preserved rows survive. - The
(+)operator expresses outer joins in the comma syntax, with several restrictions. USINGandNATURAL JOINshorten the condition when column names match.- Joining three or more tables applies the same model repeatedly, two sources at a time.
- A cross join drops the condition and returns the whole Cartesian product on purpose.
Clean Up
Remove the demo tables when you finish. Drop the child table first, because it holds the foreign key.
DROP TABLE emp_demo;
DROP TABLE dept_demo;Exercises
Exercise
The table empdemo has 4 rows and deptdemo has 3 rows. How many pairs does Oracle conceptually form before applying the join condition, and why does the inner join on dept_id return only 3 rows?
Show answer
It forms 4 x 3 = 12 pairs. Only 3 pairs have equal deptid values (Ana with Sales, Ben with Sales, Chen with IT). Dara's deptid is NULL, so comparing it to any department gives unknown, and those pairs are discarded. Legal has no employees, so no pair with it passes the condition.
Exercise
A colleague writes SELECT e.lastname, d.departmentname FROM employees e, departments d; and gets far more rows than expected. What went wrong, and how would the ANSI syntax have prevented it?
Show answer
The WHERE clause with the join condition is missing, so Oracle returns the full Cartesian product (every employee paired with every department). Written as employees e INNER JOIN departments d, the query would need an ON clause. Leaving it out is a syntax error, so the mistake would be caught before any rows came back.
Exercise
You run SELECT departmentid FROM employees e JOIN departments d ON e.departmentid = d.department_id; and get ORA-00918. Why, and what is the fix?
Show answer
Both tables have a departmentid column, so the unqualified name is ambiguous. Qualify it with an alias, for example e.departmentid or d.department_id.