Duration: 2 hours (Lecture: 2 hours, Lab: 2 hours)
Syllabus Topics:
WHERE
, SELECT
, or FROM
clauses.=
, >
, <
).
SELECT name FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);
.IN
, ANY
, ALL
).
SELECT name FROM employees WHERE dept_id IN (SELECT dept_id FROM departments WHERE budget > 100000);
.A subquery that references columns from the outer query, executed repeatedly for each row of the outer query.
Example: Find employees with salaries above their department’s average:
SELECT name, salary
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e.dept_id);
Key Notes:
EXISTS:
Tests whether a subquery returns at least one row.
Returns TRUE
if the subquery has results, FALSE
otherwise.
Example: Find departments with at least one employee:
SELECT dept_name
FROM departments d
WHERE EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id);
NOT EXISTS:
Returns TRUE
if the subquery returns no rows.
Example: Find departments with no employees:
SELECT dept_name
FROM departments d
WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id);
Key Notes:
EXISTS
is more efficient than IN
for large datasets, as it stops processing once a match is found.SELECT
clause is irrelevant (e.g., SELECT 1
or SELECT *
).COMMIT;
.ROLLBACK;
.SAVEPOINT savepoint_name;
, ROLLBACK TO savepoint_name;
.MySQL’s InnoDB
engine supports transactions; MyISAM
does not.
Use START TRANSACTION;
to begin a transaction explicitly.
Example:
START TRANSACTION;
INSERT INTO employees (emp_id, name) VALUES (1, 'Alice');
SAVEPOINT sp1;
UPDATE employees SET name = 'Bob' WHERE emp_id = 1;
ROLLBACK TO sp1; -- Reverts to Alice
COMMIT; -- Saves Alice