Sub topic 2
Inner joins: ANSI syntax and the comma syntax side by side
This chapter assumes you can write a basic SELECT with WHERE and ORDER BY, and that you know what primary and foreign keys are. You should also know how to alias a table and how NULL behaves in comparisons. The examples use the Oracle HR sample schema, where employees.department_id is a foreign key to departments.department_id.
What an inner join returns
A join combines rows from two row sources. The join condition decides which row from one source pairs with which row from the other. An inner join keeps only the pairs for which the condition is true. A row with no partner on the other side does not appear in the result.
Conceptually, Oracle compares every row of one table against every row of the other and keeps the pairs that satisfy the condition. The optimizer does not execute it that way. It picks a nested loops, hash or sort-merge join based on statistics and indexes. Your syntax choice does not force a join method.
The ANSI syntax
The ANSI form puts the join condition in an ON clause, next to the table it joins.
SELECT e.employee_id, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;Each part has a job:
FROM employees enames the first row source and gives it the aliase.INNER JOIN departments dadds a second row source with the aliasd.ON ...holds the condition that pairs rows.
The keyword INNER is optional. JOIN alone means an inner join, so FROM employees e JOIN departments d ON ... returns the same rows. Many teams drop INNER. Others keep it so the join type is explicit. Choose one style and use it consistently.
The comma syntax
Before Oracle 9i, this was the only form Oracle supported. You list the tables in FROM, separated by commas, and put the join 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;This returns the same rows as the ANSI query. Oracle parses both into the same internal join, and they normally get the same execution plan. You will still meet the comma form in older applications, in scripts, and in code that uses the (+) operator. That operator is covered in later chapters.
Side by side
| Aspect | ANSI syntax | Comma syntax |
|---|---|---|
| Where the join condition goes | `ON` clause | `WHERE` clause |
| Join type is stated | Yes: `JOIN`, `LEFT JOIN` and so on | No, it is implied |
| Join conditions vs. filters | Separated by clause | Mixed in one `WHERE` |
| Forgotten join condition | Syntax error (`ON` is required) | Silent Cartesian product |
| Outer joins | `LEFT`, `RIGHT`, `FULL OUTER JOIN` | Only through `(+)` |
| Standard | SQL standard | Oracle-specific for outer joins |
The fourth row matters most in practice, and a later section shows why.
Adding filters
Because an inner join discards non-matching pairs, a filter on either table gives the same result in ON or in WHERE. Both queries below return the same rows.
SELECT e.last_name, d.department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
WHERE e.salary > 10000;SELECT e.last_name, d.department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
AND e.salary > 10000;This equivalence holds only for inner joins. With outer joins, the position of a filter changes the result. That difference is the subject of a later chapter, so for now keep join conditions in ON and row filters in WHERE. Following that rule makes the later change to outer joins safe.
Which rows disappear
Inner joins can drop rows silently. In the standard HR schema there are 107 employees. One of them, Kimberely Grant, has a NULL department_id. The condition NULL = anything is neither true nor false. It is unknown, and a join keeps only rows where the condition is true. So the inner join above returns 106 rows, not 107.
Departments without employees disappear for the same reason. You can check what was dropped with a count comparison.
SELECT COUNT(*) AS employees_total,
(SELECT COUNT(*)
FROM employees e
JOIN departments d ON e.department_id = d.department_id) AS employees_joined
FROM employees;If the two numbers differ and you did not expect it, look for NULL foreign keys or values with no parent row. If you need to keep the unmatched rows, use an outer join, which is the next chapter's topic.
Qualifying columns and using aliases
Both tables have a department_id column. If you reference it without a prefix, Oracle cannot tell which one you mean.
SELECT employee_id, last_name, department_id
FROM employees e
JOIN departments d ON e.department_id = d.department_id;This fails with ORA-00918: column ambiguously defined. Prefix the column with its alias (e.department_id) to fix it. Columns that exist in only one table, such as last_name, do not need a prefix. Qualifying every column is still a good habit, because it shows the reader where each column comes from. It also keeps the query working if someone later adds a same-named column to the other table.
Once you alias a table, you must use the alias everywhere in that query. This fails:
SELECT employees.last_name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;Oracle reports ORA-00904: "EMPLOYEES"."LAST_NAME": invalid identifier, because after aliasing, the name employees no longer exists in that query block.
Joining on a non-key column
The join condition can be any expression that compares columns, not only a foreign key to a primary key. This is allowed, but check the result carefully. If the columns on both sides contain repeated values, each row on one side pairs with every matching row on the other side.
SELECT e1.last_name AS first_person,
e2.last_name AS second_person,
e1.job_id
FROM employees e1
JOIN employees e2
ON e1.job_id = e2.job_id
AND e1.employee_id < e2.employee_id;This lists each pair of employees who share a job, once per pair. Without the second condition, every employee would also pair with themselves and each pair would show up twice. Self joins have their own chapter, but the example shows the general point. The row count of a join is the number of matching pairs, not the row count of either table.
The forgotten join condition
This is the most common error in the comma syntax. Suppose you list two tables and forget the join condition.
SELECT e.last_name, d.department_name
FROM employees e, departments d;Oracle raises no error. It pairs every employee with every department. With 107 employees and 27 departments, that is 2,889 rows. The result is a Cartesian product, and it looks plausible until you read the data. On large tables, it can run for a long time or fill temporary space.
In ANSI syntax, the same mistake is a syntax error, because JOIN requires ON or USING. The error appears when you run the statement, not after you have misread the output.
Mixing the two syntaxes
Oracle allows both forms in one FROM clause, but the combination is a trap. An ANSI JOIN binds more tightly than the comma, so its ON clause can only see the tables in the join it belongs to.
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d
JOIN locations l ON d.location_id = l.location_id
WHERE e.department_id = d.department_id;This works because the ON clause refers only to d and l. If you write ON e.department_id = l.location_id, it fails with ORA-00904, because e is not part of that join. The simplest rule is not to mix them. Pick one syntax per query block. When you maintain an old comma-style query, convert it fully rather than adding a single ANSI JOIN to it.
Which should you write
For new code, use ANSI syntax. It states the join type, keeps join logic apart from filters, and rejects a missing join condition. It is also the only way to write a full outer join. You still need to read the comma syntax, because years of existing Oracle code use it. Reading it is easy: take each WHERE condition that compares columns from two different tables as a join condition, and treat the rest as filters.
Exercise
A query reads FROM orders o, customers c WHERE o.status = 'OPEN' and returns far more rows than orders exist. What is wrong, and how would you write it in ANSI syntax if orders.customerid references customers.customerid?
Show answer
The WHERE clause has a filter but no join condition, so every order pairs with every customer (a Cartesian product). The ANSI form is: SELECT ... FROM orders o JOIN customers c ON o.customerid = c.customerid WHERE o.status = 'OPEN'. The ON clause holds the join condition, and the status filter stays in WHERE.
Exercise
In the HR schema, SELECT COUNT(*) FROM employees returns 107, but the same count over employees JOIN departments ON the department_id columns returns 106. Why, and what kind of join would return 107?
Show answer
One employee has a NULL departmentid. The comparison NULL = departmentid is unknown, not true, so that row has no match and the inner join drops it. A LEFT OUTER JOIN from employees to departments keeps every employee, showing NULL for the department columns when there is no match.