A head office in Motijheel keeps two registers. The staff register lists every employee with a salary and a department number. The department register lists each department number with its name and city. One morning the GM asks for "each department's name with its average salary". Rafiq, the officer, sits down with both registers. For each employee he takes the department number, finds that number in the other register to read the name, then sorts the names into piles and averages each pile. Then the GM adds: "And who earns more than the average of his own department?" Now Rafiq must go back to each person and compare him with his own pile. And the new Operations department, which has no staff yet, never appears on his list at all. That missing department is the examiners' favourite trap.
Rafiq's work is exactly what SQL does when it joins two tables, groups the result and runs a query inside another query. By the end of this chapter you will be able to write a join in every form the exams use, predict how many rows each kind of join returns, choose between inner and outer joins, avoid the three classic join traps, and join a table to itself. You will write subqueries with IN, EXISTS, ANY and ALL, write a correlated subquery and explain how it runs, and find the nth highest salary in three different ways. Last, you will combine results with UNION, INTERSECT and EXCEPT, and answer the whole family of Employee-Department questions with a routine you can trust. The chapter has eight parts. You will use the previous lesson's SELECT, WHERE, GROUP BY and HAVING throughout; when one of them matters, it is recalled briefly where it is used.