emp has 10 rows (Jose has dept_id NULL) and dept has 4 rows (Operations has no employees). Predict the number of rows of: inner join, LEFT (emp → dept), RIGHT, FULL, CROSS, and emp NATURAL JOIN project.
Joins combine rows from several tables: inner joins keep matches, outer joins also keep unmatched rows padded with NULLs, cross joins pair everything and self joins relate a table to itself. Views are named stored queries that simplify, secure and decouple programs from base tables.
A LEFT JOIN B … WHERE B.key IS NULL finds A rows without a match (anti-join); filtering B in WHERE turns a LEFT JOIN into an inner join.Normalization spreads facts over several tables, so most questions need data from more than one of them. A join combines rows of two tables that satisfy a join condition — usually that a foreign key equals the primary key it references. The inner join keeps only the pairs that match.
SELECT e.ename, d.dname, d.location
FROM emp e
INNER JOIN dept d ON e.dept_id = d.dept_id; -- INNER is optional: JOIN means inner join
-- 9 rows: Jose (dept_id NULL) and Operations (no employee) are missing
-- the same join in the older comma style (SQL-89)
SELECT e.ename, d.dname FROM emp e, dept d WHERE e.dept_id = d.dept_id;
-- USING: join on the same-named column, which then appears once
SELECT dept_id, ename, dname FROM emp JOIN dept USING (dept_id) WHERE dept_id = 10;
-- 10 | Anil | Accounts 10 | Hari | AccountsFor inner joins, ON and WHERE conditions are interchangeable — the optimizer treats them alike — but keeping join conditions in ON and filters in WHERE makes queries readable and avoids accidental Cartesian products when a condition is forgotten. With USING the joined column has no table prefix (write dept_id, not e.dept_id).
A join whose condition uses only = is an equi-join; any other comparison gives a non-equi (theta) join. Classic example: grading salaries against ranges.
WITH salgrade(grade, lo, hi) AS
(VALUES (1, 0, 24999), (2, 25000, 39999), (3, 40000, 59999), (4, 60000, 99999))
SELECT e.ename, e.salary, g.grade
FROM emp e JOIN salgrade g ON e.salary BETWEEN g.lo AND g.hi
ORDER BY g.grade DESC, e.salary DESC;
-- grade 4: Anil, Bindu grade 3: Charles, Divya, Eby
-- grade 2: Fathima, Gopal, Jose grade 1: Hari, InduA NATURAL JOIN automatically equates all columns that have the same name in both tables and shows each of them once. emp NATURAL JOIN dept works as intended because the only shared name is dept_id. The danger is that the join condition is chosen by column names, not by meaning.
JOIN … ON (or USING with named columns) in real code.An outer join returns the inner-join result plus the rows that found no partner, filling the missing side's columns with NULL. LEFT keeps every row of the left table, RIGHT every row of the right table, FULL every row of both.
| Query | Rows | Extra rows beyond the 9 matches |
|---|---|---|
emp e LEFT JOIN dept d ON e.dept_id = d.dept_id | 10 | Jose | NULL |
emp e RIGHT JOIN dept d ON e.dept_id = d.dept_id | 10 | NULL | Operations |
emp e FULL OUTER JOIN dept d ON e.dept_id = d.dept_id | 11 | Jose | NULL and NULL | Operations |
SELECT e.ename, d.dname FROM emp e LEFT JOIN dept d ON e.dept_id = d.dept_id
UNION -- UNION removes the duplicated matches
SELECT e.ename, d.dname FROM dept d LEFT JOIN emp e ON e.dept_id = d.dept_id;
-- 11 rows, the same as FULL OUTER JOIN
-- Oracle's old outer-join operator: (+) marks the side that may be missing
SELECT e.ename, d.dname FROM emp e, dept d WHERE e.dept_id = d.dept_id(+); -- = LEFT JOINSQLite supports RIGHT and FULL OUTER JOIN only from version 3.39 (2022); MySQL has never supported FULL OUTER JOIN, hence the UNION idiom. A RIGHT JOIN can always be rewritten as a LEFT JOIN by swapping the tables.
dept d LEFT JOIN emp e ON e.dept_id = d.dept_id AND e.salary > 50000 returns 4 rows (Accounts–Anil, Research–Bindu, Sales–Charles, Operations–NULL). Moving e.salary > 50000 into WHERE returns 3 rows: Operations' NULL salary fails the test, so the outer join has effectively become an inner join.The anti-join idiom finds rows with no partner: SELECT d.dname FROM dept d LEFT JOIN emp e ON e.dept_id = d.dept_id WHERE e.emp_id IS NULL returns Operations. Test a column that can never be NULL in a matched row — the joined table's primary key is ideal.
A CROSS JOIN is the Cartesian product: every row of one table with every row of the other, m × n rows. emp CROSS JOIN dept returns 10 × 4 = 40 rows. It is useful for generating combinations — every employee with every project, to compare against works_on and find missing assignments — and is what you get by accident when a join condition is forgotten.
A self join joins a table to itself through two aliases, letting each row be compared with other rows of the same table. The employee–manager hierarchy stored in emp.manager_id is the textbook case.
-- each employee with the name of their manager
SELECT e.ename AS employee, m.ename AS manager
FROM emp e JOIN emp m ON e.manager_id = m.emp_id;
-- 9 rows: Bindu-Anil, Charles-Anil, Divya-Bindu, Eby-Bindu, Fathima-Charles,
-- Gopal-Charles, Hari-Anil, Indu-Divya, Jose-Charles
-- use LEFT JOIN to include Anil (manager NULL): 10 rows
-- pairs of employees doing the same job, each pair listed once
SELECT e1.ename, e2.ename, e1.job
FROM emp e1 JOIN emp e2 ON e1.job = e2.job AND e1.emp_id < e2.emp_id;
-- Bindu-Charles (Manager), Divya-Eby (Analyst), Fathima-Gopal (Salesman),
-- Hari-Indu, Hari-Jose, Indu-Jose (Clerk) → 6 pairsThe condition e1.emp_id < e2.emp_id removes both self-pairs (Hari–Hari) and mirror pairs (Indu–Hari after Hari–Indu). Without it the query returns every ordered pair including self-pairs — Σ(group size)² = 1 + 4 + 4 + 4 + 9 = 22 rows; using <> instead of < drops the 10 self-pairs but still lists each pair twice (12 rows).
SELECT e.ename, p.pname, w.hours, d.dname AS project_dept
FROM emp e
JOIN works_on w ON w.emp_id = e.emp_id
JOIN project p ON p.proj_id = w.proj_id
JOIN dept d ON d.dept_id = p.dept_id
ORDER BY e.ename, p.pname;
-- 12 rows, e.g. Bindu | CRM | 10 | Sales, Eby | Payroll | 20 | Accounts, Gopal | CRM | NULL | SalesJoins are associative and commutative for inner joins, so the optimizer is free to choose the order; for outer joins the order matters. A query joining n tables needs at least n − 1 join conditions — fewer means a Cartesian product somewhere.
| Join (|R| = m, |S| = n) | Minimum rows | Maximum rows |
|---|---|---|
| CROSS JOIN | m·n | m·n |
| INNER JOIN | 0 | m·n (every pair matches) |
| INNER JOIN on a NOT NULL FK of R to the PK of S | m | m |
| LEFT OUTER JOIN | m | m·n (n ≥ 1) |
| RIGHT OUTER JOIN | n | m·n (m ≥ 1) |
| FULL OUTER JOIN | max(m, n) | m·n, or m + n if nothing matches and that is larger |
SELECT d.dname, COUNT(*), COUNT(e.emp_id) FROM dept d LEFT JOIN emp e … GROUP BY d.dept_id, d.dname gives Operations COUNT(*) = 1 but COUNT(e.emp_id) = 0 — the NULL-padded row is still a row. Count a column from the optional side.A view is a named query stored in the data dictionary that can be used like a table. It normally stores no data: each time it is queried, the DBMS substitutes its definition into the query (view resolution or query modification) and runs the combined statement against the base tables, so a view always shows current data.
-- security: hide salary, hire_date and manager_id
CREATE VIEW emp_public AS
SELECT emp_id, ename, job, dept_id FROM emp;
-- simplification: a ready-made report
CREATE VIEW dept_summary AS
SELECT d.dname, COUNT(e.emp_id) AS staff, SUM(e.salary) AS payroll
FROM dept d LEFT JOIN emp e ON e.dept_id = d.dept_id
GROUP BY d.dept_id, d.dname;
SELECT * FROM dept_summary WHERE staff > 2;
-- Research | 4 | 180000 Sales | 3 | 113000
-- resolved as: SELECT … FROM (the dept_summary query) WHERE staff > 2
DROP VIEW IF EXISTS emp_public;
-- Oracle / MySQL / PostgreSQL: CREATE OR REPLACE VIEW emp_public AS … (SQLite: drop, then create)An INSERT, UPDATE or DELETE on a view must be translated into a change of exactly one row in a base table. That is only unambiguous for simple views. Under the SQL-92 rules — which products extend slightly — a view is updatable when:
emp_public is updatable in Oracle, MySQL and PostgreSQL; dept_summary is not, because each of its rows summarises many base rows. Oracle also allows changes to join views for a key-preserved table (one whose key stays unique in the join), one base table per statement. SQLite treats every view as read-only ('cannot modify emp_public because it is a view') unless an INSTEAD OF trigger supplies the translation — see the Triggers topic.
CREATE VIEW research_emp AS
SELECT emp_id, ename, job, salary, dept_id FROM emp WHERE dept_id = 20
WITH CHECK OPTION;
UPDATE research_emp SET salary = salary + 1000 WHERE ename = 'Divya'; -- OK: row stays in dept 20
UPDATE research_emp SET dept_id = 30 WHERE ename = 'Divya'; -- rejected: row would leave the view
INSERT INTO research_emp VALUES (111, 'Kiran', 'Clerk', 21000, 10); -- rejected: dept_id 10 is not 20Without CHECK OPTION the second statement would succeed and Divya would vanish from research_emp — a 'migrating row'. WITH LOCAL CHECK OPTION checks only this view's condition; WITH CASCADED CHECK OPTION (the default when you just write WITH CHECK OPTION) also checks the conditions of the views it is built on.
A materialized view stores the result of its query physically, like a table, so reading it is fast — ideal for expensive aggregations in reporting and data warehouses. The price is staleness: the stored result must be refreshed when base tables change.
-- Oracle
CREATE MATERIALIZED VIEW dept_payroll_mv
BUILD IMMEDIATE
REFRESH FAST ON COMMIT -- or COMPLETE ON DEMAND; FAST needs materialized-view logs
AS SELECT dept_id, COUNT(*) AS staff, SUM(salary) AS payroll FROM emp GROUP BY dept_id;
-- PostgreSQL
CREATE MATERIALIZED VIEW dept_payroll_mv AS
SELECT dept_id, COUNT(*) AS staff, SUM(salary) AS payroll FROM emp GROUP BY dept_id;
REFRESH MATERIALIZED VIEW dept_payroll_mv; -- complete refresh, run when neededRefresh choices: complete (re-run the whole query) or fast/incremental (apply only the changes recorded in a log); on commit (always current, slows every transaction) or on demand / scheduled (cheap, may be stale). In SQLite or MySQL the same effect is built with a summary table kept current by triggers or a scheduled job.
Try the problem first, then reveal the working one step at a time.
emp has 10 rows (Jose has dept_id NULL) and dept has 4 rows (Operations has no employees). Predict the number of rows of: inner join, LEFT (emp → dept), RIGHT, FULL, CROSS, and emp NATURAL JOIN project.
Compare A: dept d LEFT JOIN emp e ON e.dept_id = d.dept_id AND e.salary > 50000, and B: dept d LEFT JOIN emp e ON e.dept_id = d.dept_id WHERE e.salary > 50000. Which departments appear and why?
research_emp is defined as SELECT emp_id, ename, job, salary, dept_id FROM emp WHERE dept_id = 20 WITH CHECK OPTION. Predict each statement: (1) give Divya a raise through the view; (2) move Divya to department 30 through the view; (3) insert employee 111 with dept_id 10 through the view; (4) the same as (2) on a view without CHECK OPTION.
Write a query listing every project with its number of workers and total hours, so that a project with no workers would show 0 workers. What is the result on the sample data?
How many rows do these return? (a) emp CROSS JOIN project; (b) emp NATURAL JOIN works_on; (c) dept NATURAL JOIN project; (d) emp e JOIN emp m ON e.manager_id = m.emp_id.
Is the view dept_summary (department name, COUNT of staff and SUM of salary from dept LEFT JOIN emp, grouped by department) updatable? Give two reasons.
Using the salary-grade ranges 1: 0–24999, 2: 25000–39999, 3: 40000–59999, 4: 60000–99999 (salaries are whole rupees), write the non-equi join that lists employees with their grade and give the employees in grade 2.
R has 6 rows and S has 4 rows. Exactly 3 rows of R each match exactly one different row of S; nothing else matches. How many rows do R ⋈ S, R LEFT JOIN S, R RIGHT JOIN S and R FULL JOIN S return?
COUNT(*) after an outer join counts NULL-padded rows; count a column of the optional table to get 0.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.