Database ProgrammingUnit 98 min read
SQL Advanced Topics: Subqueries, Joins, DDL Commands & Real-World Database Logic
Unit 9 of Database Programming explores how to write complex SQL queries using subqueries (nested queries), master joins (inner/outer/cross), and DDL commands (CREATE/ALTER/DROP) that build real databases. You’ll learn how to chain queries, combine tables, and modify database structures—skills used daily by banks, e-co
Core Concepts: Subqueries, Joins, and DDL
1. Subqueries: Nested Queries for Complex Logic
Subqueries are queries inside queries that return a single value, a set of values, or a table. They help break down complex problems into smaller, manageable parts.
Types of Subqueries
mindmap
root((Subqueries))
Single-Row Subquery
"Returns one value (e.g., MAX, MIN, COUNT)"
Example: `WHERE salary > (SELECT AVG(salary) FROM employees)`
Multi-Row Subquery
"Returns multiple rows (e.g., IN, ANY, ALL)"
Example: `WHERE dept_id IN (SELECT dept_id FROM departments WHERE location = 'Kathmandu')`
Correlated Subquery
"Depends on the outer query (runs for each row)"
Example: `SELECT e.name FROM employees e WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id)`Key Uses of Subqueries
- Filtering:
WHERE salary > (SELECT AVG(salary) FROM employees) - Comparison:
WHERE dept_id IN (SELECT dept_id FROM departments WHERE budget > 1000000) - Existence Check:
WHERE EXISTS (SELECT 1 FROM orders WHERE customer_id = e.customer_id)
Example: Finding Employees Earning More Than Their Department’s Average
SELECT name, salary, dept_id
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id);
Output:
| NAME | SALARY | DEPT_ID |
|---|---|---|
| John Doe | 80000 | 10 |
| Jane Smith | 90000 | 20 |
2. Joins: Combining Tables
Joins combine rows from two or more tables based on related columns. They are essential for retrieving data spread across multiple tables.
Types of Joins
| Join Type | Symbol | Description | Example |
|---|---|---|---|
| INNER JOIN | INNER JOIN |
Returns rows where there is a match in both tables. | SELECT * FROM employees INNER JOIN departments ON employees.dept_id = departments.dept_id; |
| LEFT (OUTER) JOIN | LEFT JOIN |
Returns all rows from the left table and matched rows from the right. | SELECT * FROM employees LEFT JOIN departments ON employees.dept_id = departments.dept_id; |
| RIGHT (OUTER) JOIN | RIGHT JOIN |
Returns all rows from the right table and matched rows from the left. | SELECT * FROM employees RIGHT JOIN departments ON employees.dept_id = departments.dept_id; |
| FULL (OUTER) JOIN | FULL JOIN |
Returns all rows when there is a match in either table. | SELECT * FROM employees FULL JOIN departments ON employees.dept_id = departments.dept_id; |
| CROSS JOIN | CROSS JOIN |
Returns the Cartesian product (all possible combinations). | SELECT * FROM employees CROSS JOIN departments; |
| NATURAL JOIN | NATURAL JOIN |
Joins tables on columns with identical names (avoid unless necessary). | SELECT * FROM employees NATURAL JOIN departments; |
| SELF JOIN | JOIN ... ON |
Joins a table to itself (e.g., employee-manager hierarchy). | SELECT a.name AS employee, b.name AS manager FROM employees a JOIN employees b ON a.manager_id = b.emp_id; |
Output:
| NAME | DEPT_NAME | SALARY |
|---|---|---|
| John Doe | IT | 80000 |
| Jane Smith | HR | 75000 |
Example: LEFT JOIN (All Employees, Even Without Departments)
SELECT employees.name, departments.dept_name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.dept_id;
Output (includes employees with no department):
| NAME | DEPT_NAME |
|---|---|
| John Doe | IT |
| Jane Smith | HR |
| Bob Lee | NULL |
3. DDL Commands: Defining and Modifying Database Structure
DDL (Data Definition Language) commands create, modify, or delete database objects (tables, indexes, constraints).
Key DDL Commands
| Command | Purpose | Example |
|---|---|---|
CREATE |
Creates a new database object (table, index, view). | CREATE TABLE employees (emp_id INT PRIMARY KEY, name VARCHAR(50)); |
ALTER |
Modifies an existing object (add/drop columns, constraints). | ALTER TABLE employees ADD COLUMN salary DECIMAL(10,2); |
DROP |
Deletes an object permanently. | DROP TABLE temp_employees; |
TRUNCATE |
Removes all rows from a table (faster than DELETE). | TRUNCATE TABLE employees; |
RENAME |
Renames a table or column (Oracle: RENAME; MySQL: ALTER TABLE ... RENAME). |
RENAME employees TO staff; (Oracle) |
COMMENT |
Adds descriptive text to tables/columns. | COMMENT ON TABLE employees IS 'Stores employee records'; |
Example: Altering a Table to Add a Column
ALTER TABLE employees
ADD COLUMN email VARCHAR(100) UNIQUE;
In the Real World
eSewa (Nepal Government)
- Subqueries: When checking if a user has unpaid bills, eSewa runs:
SELECT user_id FROM users WHERE EXISTS (SELECT 1 FROM bills WHERE user_id = users.user_id AND status = 'Pending'); - Joins: Combining
users,transactions, andbillstables to show a user’s payment history.
- Subqueries: When checking if a user has unpaid bills, eSewa runs:
Daraz (E-Commerce)
- LEFT JOIN: When displaying orders, Daraz uses:
→ Shows all orders, even if the user or product is deleted.SELECT o.order_id, u.username, p.product_name, o.status FROM orders o LEFT JOIN users u ON o.user_id = u.user_id LEFT JOIN products p ON o.product_id = p.product_id;
- LEFT JOIN: When displaying orders, Daraz uses:
NTC (Nepal Telecom)
- DDL: NTC’s database schema is built using
CREATE TABLEforcustomers,plans, andbills. When adding a new plan, they use:ALTER TABLE plans ADD COLUMN discount_percentage DECIMAL(5,2);
- DDL: NTC’s database schema is built using
Visual: How Joins Work
Exam Tip
Subqueries:
- Always check if the subquery returns one value (use
=,<,>) or multiple values (useIN,ANY,ALL). - Correlated subqueries are common in exams—practice rewriting them with
EXISTS.
- Always check if the subquery returns one value (use
Joins:
- INNER JOIN = "Only matching rows."
- OUTER JOIN = "All rows from one table + matches."
- CROSS JOIN = "Every possible combination" (rarely used in real systems).
- Draw a Venn diagram in your exam to visualize joins.
DDL:
DROPis permanent—unlikeDELETE, it cannot be rolled back.TRUNCATEis faster thanDELETEbut resets auto-increment counters.- Constraints (
PRIMARY KEY,FOREIGN KEY,UNIQUE) are often tested—know their syntax.
Common Mistakes to Avoid:
- Forgetting
ONin JOIN conditions. - Using
NATURAL JOINwithout knowing column names. - Mixing up
LEFTandRIGHTjoins.
- Forgetting
Practice Question:
Write a query to find all customers who have placed orders but have no pending payments (use NOT EXISTS).
Answer:
SELECT customer_id, name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND NOT EXISTS (
SELECT 1 FROM payments p
WHERE p.order_id = o.order_id AND p.status = 'Pending'
)
);
Based on the TU BCA syllabus for Database Programming (CACS484), unit 9.
Discussion
Loading…