Module 3 · Introduction to SQL
The language every relational database speaks: its data types and operators, its four families of commands, how the database processes a query, and how to ask real questions — with joins, sub-queries and recursive queries — and package queries as views and logic as functions, procedures and triggers.
Your Module III lecture notes use MySQL — this module uses PostgreSQL
The ideas are the same in every relational database, but some syntax differs. Everything here is PostgreSQL, the database we use in the lab, and every example was run on university_lab. Where MySQL differs, a table in 3.4 shows both side by side.
- ▸ Choose data types and use SQL operators correctly, including NULL
- ▸ Classify SQL commands as DDL, DML, DCL or TCL
- ▸ Explain how a query is parsed, planned and executed
- ▸ Write queries with filtering, grouping, joins and sub-queries
- ▸ Walk a hierarchy with a recursive query
- ▸ Use bind variables and cursors
- ▸ Create views and materialized views
- ▸ Write functions, stored procedures and triggers
The inter schema of university_lab with the sample rows. Examples that change data run inside BEGIN … ROLLBACK, and the functions and procedures you create end with a tidy-up step. Views and triggers are tried inside a transaction and rolled back.
3.1 Introduction to SQL & Its Features
| Feature | What it means |
|---|---|
| Declarative | You say WHAT data you want, not HOW to find it. The database decides how. |
| Set-based | One statement works on many rows at once. |
| Complete | One language defines structure (DDL), changes data (DML), controls access (DCL) and manages transactions (TCL). |
| Standard and portable | The core is the same in PostgreSQL, Oracle, MySQL and SQL Server; each adds its own extensions. |
| English-like | Statements read almost like sentences: SELECT … FROM … WHERE … |
| Embeddable | Used from Python, Java and other languages, and inside the database in functions and procedures. |
SELECT full_name
FROM inter.students
WHERE join_year = 2024
ORDER BY full_name;
full_name
-----------------
Aarav Menon
Ananya Krishnan
Diya Nair
Fatima RahmanNothing here says which file to open, whether to use an index, or how to sort. The database works that out (see 3.5).
- ▸SQL is declarative, set-based, standard, and covers definition, manipulation, control and transactions.
- ▸Each RDBMS speaks a dialect: the same core with small differences (PostgreSQL vs MySQL).
3.2 SQL Data Types
| Category | PostgreSQL | MySQL name (Module III) | Use for |
|---|---|---|---|
| Whole numbers | smallint · integer · bigint | TINYINT, SMALLINT · MEDIUMINT, INT · BIGINT | Counts, years, ids |
| Exact decimals | numeric(p,s) / decimal(p,s) | DECIMAL | Money, marks, GPA |
| Approximate decimals | real · double precision | FLOAT · DOUBLE | Scientific measurements |
| Auto-numbering | serial, or integer GENERATED AS IDENTITY | AUTO_INCREMENT | Surrogate primary keys |
| Text | char(n) · varchar(n) · text | CHAR · VARCHAR · TINYTEXT … LONGTEXT | Codes, names, long text |
| Binary | bytea | BINARY, VARBINARY, BLOB family | Files, images |
| Date and time | date · time · timestamp · timestamptz · interval | DATE · TIME · DATETIME · TIMESTAMP · (none) | Dates, moments, durations |
| Yes / no | boolean | BOOLEAN (stored as TINYINT(1)) | Flags |
| Fixed list of values | CREATE TYPE … AS ENUM, or a CHECK | ENUM · SET | Status codes |
| Modern extras | uuid · jsonb · arrays (text[]) | JSON | Unique ids, documents, lists |
SELECT pg_typeof(42), pg_typeof(4.5), pg_typeof('CS201'::varchar),
pg_typeof(DATE '2024-07-01'), pg_typeof(now()), pg_typeof(true);
integer | numeric | character varying | date | timestamp with time zone | booleanSELECT 7 / 2 AS int_division,
7 / 2.0 AS exact_division,
DATE '2024-11-30' - DATE '2024-07-01' AS semester_days,
INTERVAL '1 day' * 7 AS one_week;
int_division | exact_division | semester_days | one_week
--------------+--------------------+---------------+----------
3 | 3.5000000000000000 | 152 | 7 days- ▸Exact values (marks, money) → numeric; never real/float.
- ▸Text with a sensible limit → varchar(n); otherwise text. Dates → date; moments → timestamptz.
- ▸Integer ÷ integer gives an integer in PostgreSQL: 7 / 2 = 3.
3.3 SQL Operators
WHERE clause to build conditions.| Kind | Operators | Example on university_lab |
|---|---|---|
| Arithmetic | + − * / % (modulus) ^ (power) | credits * 15 |
| Comparison | = <> != < > <= >= | credits >= 4 |
| Logical | AND OR NOT | credits >= 4 AND course_code LIKE 'CS%' |
| Range | BETWEEN a AND b (inclusive) | join_year BETWEEN 2023 AND 2024 |
| List | IN (…) NOT IN (…) | course_code IN ('CS101', 'MA101') |
| Pattern | LIKE (case-sensitive) · ILIKE (PostgreSQL, case-insensitive); % = any text, _ = one character | email LIKE 'a%' |
| NULL test | IS NULL IS NOT NULL | faculty_id IS NULL |
| Sub-query | EXISTS · ANY / SOME · ALL | credits > ALL (SELECT …) |
| Text | || (concatenate) | full_name || ' <' || email || '>' |
SELECT course_code, credits, credits * 15 AS contact_hours
FROM inter.courses ORDER BY course_code;
course_code | credits | contact_hours
-------------+---------+---------------
CS101 | 4 | 60
CS201 | 4 | 60
CS210 | 3 | 45
DA301 | 4 | 60
MA101 | 3 | 45SELECT course_code, title FROM inter.courses
WHERE credits >= 4 AND course_code LIKE 'CS%'; -- CS101, CS201
SELECT full_name FROM inter.students WHERE full_name ILIKE '%NAIR%'; -- Diya Nair
-- courses worth more credits than every Mathematics course
SELECT course_code FROM inter.courses
WHERE credits > ALL (SELECT credits FROM inter.courses WHERE course_code LIKE 'MA%');
-- CS101, CS201, DA301SELECT TRUE AND NULL, FALSE AND NULL, TRUE OR NULL, NOT NULL::boolean;
?column? | ?column? | ?column? | ?column?
----------+----------+----------+----------
| f | t | <- NULL, false, true, NULLNot in PostgreSQL
The Module III lecture notes list !< and !> (“not less than” / “not greater than”) — those come from SQL Server. PostgreSQL rejects them (operator does not exist: integer !< integer); write >= and <= instead. The UNIQUE sub-query test in the notes is in the SQL standard but is not implemented by PostgreSQL either.
- ▸Comparisons with NULL give NULL (unknown); use IS NULL / IS NOT NULL.
- ▸WHERE keeps a row only when the condition is TRUE — not when it is FALSE or NULL.
- ▸LIKE is case-sensitive; ILIKE is PostgreSQL’s case-insensitive version.
3.4 Types of SQL Commands
SELECT separately as DQL (data query language).| Family | Commands | Purpose |
|---|---|---|
| DDL — Data Definition | CREATE · ALTER · DROP · TRUNCATE · COMMENT · ALTER … RENAME | Create, change and remove database objects |
| DQL — Data Query | SELECT | Read data |
| DML — Data Manipulation | INSERT · UPDATE · DELETE · MERGE | Add, change and remove rows |
| DCL — Data Control | GRANT · REVOKE | Give and take back privileges |
| TCL — Transaction Control | BEGIN · COMMIT · ROLLBACK · SAVEPOINT · ROLLBACK TO · SET TRANSACTION | Group statements into transactions |
Correction to the notes: DDL and TRUNCATE can be rolled back in PostgreSQL
The Module III lecture notes say “all DDL commands are auto-committed” and that TRUNCATE has “no rollback”. That is true of MySQL and Oracle, but not of PostgreSQL: inside a transaction, CREATE, ALTER, DROP and TRUNCATE can all be rolled back. The first two examples below prove it.
BEGIN;
CREATE TABLE inter.tasks (
task_id SERIAL PRIMARY KEY,
subject VARCHAR(45),
start_date DATE,
end_date DATE
);
ALTER TABLE inter.tasks ADD COLUMN complete NUMERIC(2,1);
ALTER TABLE inter.tasks RENAME TO work_items;
COMMENT ON TABLE inter.work_items IS 'Practice table from Module 3';
ROLLBACK;
SELECT to_regclass('inter.work_items'); -- NULL: the table never existedBEGIN;
TRUNCATE inter.enrollments;
SELECT COUNT(*) FROM inter.enrollments; -- 0
ROLLBACK;
SELECT COUNT(*) FROM inter.enrollments; -- 6 — all backBEGIN;
-- insert, or update if the course code already exists
INSERT INTO inter.courses (course_code, title, credits)
VALUES ('CS101', 'Programming in Python', 4)
ON CONFLICT (course_code) DO UPDATE SET title = EXCLUDED.title;
-- CS101 is now 'Programming in Python'
-- MERGE (PostgreSQL 15+): update the matches, insert the rest
MERGE INTO inter.courses c
USING (VALUES ('CS101', 'Introduction to Programming', 4),
('CS302', 'Compiler Design', 3)) AS v(code, title, credits)
ON c.course_code = v.code
WHEN MATCHED THEN UPDATE SET title = v.title, credits = v.credits
WHEN NOT MATCHED THEN INSERT (course_code, title, credits) VALUES (v.code, v.title, v.credits);
-- MERGE 2 (CS101 updated back, CS302 inserted)
ROLLBACK;GRANT SELECT ON inter.v_offering_roster TO faculty_reader;
REVOKE SELECT ON inter.v_offering_roster FROM faculty_reader;BEGIN;
UPDATE inter.course_offerings SET capacity = 50 WHERE room = 'LH-3';
SAVEPOINT before_delete;
DELETE FROM inter.enrollments; -- oops: every enrollment
ROLLBACK TO SAVEPOINT before_delete; -- undo only the DELETE
SELECT capacity, (SELECT COUNT(*) FROM inter.enrollments) AS enrollments
FROM inter.course_offerings WHERE room = 'LH-3';
capacity | enrollments
----------+-------------
50 | 6 <- the UPDATE survived, the DELETE did not
ROLLBACK; -- and now undo everything| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Family | DML | DDL | DDL |
| Removes | Chosen rows (WHERE), or all | All rows | The whole table: rows and structure |
| Speed on big tables | Slower — row by row | Very fast | Very fast |
| Fires row triggers | Yes | No | No |
| Rollback in PostgreSQL | Yes | Yes | Yes |
MySQL (Module III) → PostgreSQL
| Task | MySQL | PostgreSQL |
|---|---|---|
| List databases | SHOW DATABASES; | \l in psql, or SELECT datname FROM pg_database; |
| Switch database | USE university_lab; | \c university_lab |
| Create a database | CREATE DATABASE IF NOT EXISTS db; | CREATE DATABASE db; (no IF NOT EXISTS) |
| List / describe tables | SHOW TABLES; DESCRIBE students; | \dt inter.* \d inter.students |
| Auto-numbering id | id INT AUTO_INCREMENT | id SERIAL or id INTEGER GENERATED ALWAYS AS IDENTITY |
| Quote a name | `my table` | "my table" |
| Change a column | ALTER TABLE t CHANGE COLUMN a a INT NOT NULL; | ALTER TABLE t ALTER COLUMN a TYPE INT, ALTER COLUMN a SET NOT NULL; |
| Add a column in position | ADD COLUMN c … AFTER b | Not supported — new columns are added last |
| Name a foreign key | FOREIGN KEY fk_cat (cat_id) REFERENCES … | CONSTRAINT fk_cat FOREIGN KEY (cat_id) REFERENCES … |
| Index on a foreign key | Created automatically | Not automatic — create it: CREATE INDEX ON t (cat_id); |
| Upsert | INSERT … ON DUPLICATE KEY UPDATE | INSERT … ON CONFLICT … DO UPDATE or MERGE |
| Limit a DELETE | DELETE … LIMIT 10 | Not supported — use WHERE id IN (SELECT … LIMIT 10) |
- ▸DDL = structure, DQL = SELECT, DML = rows, DCL = privileges, TCL = transactions.
- ▸In PostgreSQL even DDL and TRUNCATE are transactional.
- ▸DELETE removes rows; TRUNCATE empties the table fast; DROP removes the table itself.
3.5 SQL Parsing: How a Query Is Processed
SELEC * FROM inter.students;
ERROR: syntax error at or near "SELEC"SELECT * FROM inter.student;
ERROR: relation "inter.student" does not exist
SELECT dept_id FROM inter.students, inter.courses;
ERROR: column reference "dept_id" is ambiguous -- both tables have dept_idEXPLAIN
SELECT s.full_name
FROM inter.students s
JOIN inter.enrollments e ON e.student_id = s.student_id
WHERE s.join_year = 2024;
Nested Loop
-> Seq Scan on students s
Filter: (join_year = 2024)
-> Bitmap Heap Scan on enrollments e
Recheck Cond: (s.student_id = student_id)
-> Bitmap Index Scan on enrollments_student_id_offering_id_key
Index Cond: (student_id = s.student_id)The planner used the index behind the UNIQUE (student_id, offering_id) constraint to find each student's enrollments — you never asked it to.
The logical order of a SELECT
You write SELECT first, but the database evaluates the clauses in this order:
SELECT course_code, credits * 15 AS hours FROM inter.courses WHERE hours > 50;
ERROR: column "hours" does not exist -- WHERE runs before SELECT creates "hours"
SELECT course_code, credits * 15 AS hours FROM inter.courses ORDER BY hours DESC;
-- works: ORDER BY runs after SELECT- ▸Parse (syntax) → analyse (semantics) → rewrite (views) → plan (optimiser) → execute.
- ▸EXPLAIN shows the plan; EXPLAIN ANALYZE also runs the query and shows real timings.
- ▸Logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.
3.6 Querying Data: SELECT, Filter, Sort, Group
SELECT retrieves rows from tables or views. Its clauses filter rows (WHERE), remove duplicates (DISTINCT), sort (ORDER BY), limit (LIMIT), and summarise groups of rows (GROUP BY with aggregate functions, filtered by HAVING).SELECT [DISTINCT] column_list
FROM table
WHERE row_condition
GROUP BY grouping_columns
HAVING group_condition
ORDER BY sort_columns [ASC | DESC]
LIMIT n OFFSET m;SELECT DISTINCT join_year FROM inter.students ORDER BY join_year; -- 2023, 2024
-- the two largest offerings
SELECT course_code, capacity
FROM inter.v_seat_availability
ORDER BY capacity DESC
LIMIT 2;
course_code | capacity
-------------+----------
CS101 | 40
MA101 | 30SELECT course_code, seats_left,
CASE WHEN seats_left = 0 THEN 'FULL'
WHEN seats_left < 5 THEN 'ALMOST FULL'
ELSE 'OPEN' END AS status
FROM inter.v_seat_availability
ORDER BY course_code;
course_code | seats_left | status
-------------+------------+--------
CS101 | 39 | OPEN
CS201 | 0 | FULL
DA301 | 0 | FULL
MA101 | 30 | OPENSELECT COUNT(*) AS courses, SUM(credits) AS total_credits,
MIN(credits) AS min_cr, MAX(credits) AS max_cr,
ROUND(AVG(credits), 2) AS avg_credits
FROM inter.courses;
courses | total_credits | min_cr | max_cr | avg_credits
---------+---------------+--------+--------+-------------
5 | 18 | 3 | 4 | 3.60SELECT dept_id, COUNT(*) AS courses, SUM(credits) AS credits
FROM inter.courses
GROUP BY dept_id
ORDER BY dept_id;
dept_id | courses | credits
---------+---------+---------
1 | 3 | 11 <- Computer Science
2 | 1 | 3 <- Mathematics
3 | 1 | 4 <- Data Analytics
SELECT join_year, COUNT(*) AS students
FROM inter.students
GROUP BY join_year
HAVING COUNT(*) > 2; -- 2024 | 4Set operators combine the results of two queries with the same columns: UNION (all, duplicates removed), UNION ALL (all, duplicates kept), INTERSECT (in both) and EXCEPT (in the first but not the second).
SELECT course_id FROM inter.course_offerings
INTERSECT
SELECT prereq_course_id FROM inter.prerequisites
ORDER BY 1; -- 1 (CS101), 3 (CS201)
-- swap INTERSECT for EXCEPT → 4 (MA101), 5 (DA301): offered, but nobody needs them first- ▸WHERE filters rows before grouping; HAVING filters groups after grouping.
- ▸Every column in SELECT must be inside an aggregate or listed in GROUP BY.
- ▸UNION removes duplicates; UNION ALL keeps them; INTERSECT = both; EXCEPT = first minus second.
3.7 Joins
| Join | Returns | |
|---|---|---|
| INNER JOIN | Only rows that match in both tables | |
| LEFT [OUTER] JOIN | All rows of the left table, with matches from the right (NULLs where there is none) | |
| RIGHT [OUTER] JOIN | All rows of the right table, with matches from the left | |
| FULL [OUTER] JOIN | All rows of both, matched where possible | |
| LEFT JOIN … WHERE right.key IS NULL | Rows of the left table with no match at all | |
| CROSS JOIN | Every combination of rows (Cartesian product) | |
| Self join | A table joined to itself, using two aliases |
SELECT f.full_name AS faculty, c.course_code, s.name AS semester
FROM inter.course_offerings o
JOIN inter.faculty f ON f.faculty_id = o.faculty_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters s ON s.semester_id = o.semester_id
ORDER BY faculty, c.course_code;
faculty | course_code | semester
------------------+-------------+-----------
Dr. Meera Suresh | MA101 | 2024-Even
Dr. Nisha Varma | CS101 | 2024-Odd
Dr. Nisha Varma | CS201 | 2024-Odd
Dr. Rajesh Iyer | DA301 | 2024-OddSELECT s.full_name, COUNT(e.enrollment_id) AS courses
FROM inter.students s
LEFT JOIN inter.enrollments e ON e.student_id = s.student_id
GROUP BY s.full_name
ORDER BY s.full_name;
full_name | courses
-----------------+---------
Aarav Menon | 2
Ananya Krishnan | 1
Diya Nair | 2
Fatima Rahman | 0 <- kept by the LEFT JOIN
Kevin Thomas | 1
Rohan Pillai | 0SELECT c.course_code, s.name AS semester
FROM inter.enrollments e
RIGHT JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters s ON s.semester_id = o.semester_id
WHERE e.enrollment_id IS NULL; -- MA101 | 2024-EvenSELECT COALESCE(a.code, b.code) AS course,
a.code IS NOT NULL AS offered_2024_odd,
b.code IS NOT NULL AS is_a_prerequisite
FROM (SELECT c.course_code AS code
FROM inter.course_offerings o
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters s ON s.semester_id = o.semester_id
WHERE s.name = '2024-Odd') a
FULL JOIN
(SELECT DISTINCT c.course_code AS code
FROM inter.prerequisites p
JOIN inter.courses c ON c.course_id = p.prereq_course_id) b
ON a.code = b.code
ORDER BY 1;
course | offered_2024_odd | is_a_prerequisite
--------+------------------+-------------------
CS101 | t | t
CS201 | t | t
CS210 | f | t <- only in the right list
DA301 | t | f <- only in the left list-- every department × every semester: a planning grid (3 × 2 = 6 rows)
SELECT d.dept_code, s.name AS semester
FROM inter.departments d CROSS JOIN inter.semesters s;
-- self join: students who joined in the same year as Diya
SELECT b.full_name
FROM inter.students a
JOIN inter.students b ON b.join_year = a.join_year AND b.student_id <> a.student_id
WHERE a.full_name = 'Diya Nair'
ORDER BY 1; -- Aarav Menon, Ananya Krishnan, Fatima RahmanShortcut: when both columns have the same name, JOIN … USING (course_id) replaces ON a.course_id = b.course_id. The old comma style FROM a, b WHERE a.x = b.x still works, but the JOIN keyword is clearer.
- ▸INNER = matches only. LEFT / RIGHT = all of one side. FULL = all of both. CROSS = every pair.
- ▸To find rows with no match: LEFT JOIN … WHERE right_table.key IS NULL.
- ▸A filter on the right table of a LEFT JOIN belongs in ON, or the join silently becomes INNER.
3.8 Sub-queries & Correlated Sub-queries
WHERE, FROM or the SELECT list. A non-correlated sub-query is independent: it could run on its own, and conceptually runs once.SELECT full_name FROM inter.students
WHERE dept_id = (SELECT dept_id FROM inter.departments WHERE dept_code = 'DA');
-- Ananya Krishnan, Diya NairSELECT s.full_name,
(SELECT COUNT(*) FROM inter.enrollments e
WHERE e.student_id = s.student_id) AS courses -- s comes from the outer query
FROM inter.students s
ORDER BY s.full_name;
full_name | courses
-----------------+---------
Aarav Menon | 2
Ananya Krishnan | 1
Diya Nair | 2
Fatima Rahman | 0
Kevin Thomas | 1
Rohan Pillai | 0-- courses that have at least one prerequisite
SELECT c.course_code FROM inter.courses c
WHERE EXISTS (SELECT 1 FROM inter.prerequisites p WHERE p.course_id = c.course_id);
-- CS201, DA301
-- students with no enrollment at all
SELECT s.full_name FROM inter.students s
WHERE NOT EXISTS (SELECT 1 FROM inter.enrollments e WHERE e.student_id = s.student_id);
-- Fatima Rahman, Rohan PillaiSELECT s.full_name, s.join_year
FROM inter.students s
WHERE s.join_year = (SELECT MIN(s2.join_year)
FROM inter.students s2
WHERE s2.dept_id = s.dept_id) -- "same department as this student"
ORDER BY 1;
full_name | join_year
-----------------+-----------
Ananya Krishnan | 2024 <- DA's earliest year is 2024
Diya Nair | 2024
Fatima Rahman | 2024 <- the only MA student
Kevin Thomas | 2023 <- CS's earliest year is 2023
Rohan Pillai | 2023SELECT c.course_code, o.capacity
FROM inter.course_offerings o
JOIN inter.courses c ON c.course_id = o.course_id
WHERE o.capacity <= (SELECT COUNT(*) FROM inter.enrollments e
WHERE e.offering_id = o.offering_id);
-- CS201 | 3, DA301 | 2Performance
“Evaluated for each row” is the logical meaning. The planner often rewrites a correlated EXISTS into a join, so it is usually fast. NOT EXISTS is also safer than NOT IN: if the sub-query returns a NULL, NOT IN returns no rows at all.
- ▸Non-correlated: independent, runs once. Correlated: refers to the outer row, re-evaluated per row.
- ▸EXISTS asks "is there at least one?"; NOT EXISTS asks "is there none?".
- ▸A sub-query in the SELECT list must return a single value (a scalar sub-query).
3.9 Hierarchical Queries
START WITH … CONNECT BY PRIOR; standard SQL and PostgreSQL use a recursive common table expression, WITH RECURSIVE.A recursive query has two parts joined by UNION ALL:
- Anchor — the starting rows (the root of the tree).
- Recursive step — refers to the query's own name to find the next level. It repeats until it finds no new rows.
DA301 needs CS201, and CS201 needs CS101 and CS210. One recursive query finds the whole chain, level by level:
WITH RECURSIVE chain AS (
-- anchor: start at DA301
SELECT c.course_id, c.course_code::text AS path, 0 AS level
FROM inter.courses c
WHERE c.course_code = 'DA301'
UNION ALL
-- recursive step: the prerequisites of whatever we found last time
SELECT p.prereq_course_id, ch.path || ' → ' || pc.course_code, ch.level + 1
FROM chain ch
JOIN inter.prerequisites p ON p.course_id = ch.course_id
JOIN inter.courses pc ON pc.course_id = p.prereq_course_id
)
SELECT level, path FROM chain ORDER BY level, path;
level | path
-------+-----------------------
0 | DA301
1 | DA301 → CS201
2 | DA301 → CS201 → CS101
2 | DA301 → CS201 → CS210SELECT LEVEL, course_code
FROM course_prereq_view
START WITH course_code = 'DA301'
CONNECT BY PRIOR prereq_code = course_code;Beware of cycles
If the data ever loops (A needs B, B needs A), a recursive query would run forever. Our CHECK (course_id <> prereq_course_id) only stops a course requiring itself directly. PostgreSQL 14+ can detect loops with a CYCLE clause.
- ▸WITH RECURSIVE = anchor query UNION ALL recursive step that refers to itself.
- ▸Each pass adds one level of the hierarchy; it stops when a pass adds no rows.
- ▸Oracle: START WITH / CONNECT BY PRIOR / LEVEL. Standard SQL and PostgreSQL: WITH RECURSIVE.
3.10 Bind Variables
$1, $2… in PostgreSQL, :name in Oracle, ? in JDBC — whose value is supplied separately, at execution time. The statement is parsed once and can run many times with different values, and its plan can be reused.Why use them:
- Security — a value can never be read as SQL code, so SQL injection is impossible.
- Speed — the parsing work (3.5) is done once, and the plan can be reused.
- Correctness — no quoting problems with names like O'Brien.
PREPARE student_by_email(text) AS
SELECT full_name, join_year FROM inter.students WHERE email = $1;
EXECUTE student_by_email('diya@duk.ac.in'); -- Diya Nair | 2024
EXECUTE student_by_email('kevin@duk.ac.in'); -- Kevin Thomas | 2023
DEALLOCATE student_by_email;SELECT full_name FROM inter.students WHERE email = $1 \bind 'ananya@duk.ac.in' \g
-- Ananya Krishnan-- A login form builds SQL by gluing text together, and a user types: x' OR '1'='1
-- The glued query becomes:
SELECT COUNT(*) FROM inter.students WHERE email = 'x' OR '1'='1';
-- 6 <- every student: the input changed the meaning of the query
-- With a bind variable the whole input is only ever a value:
EXECUTE student_by_email($$x' OR '1'='1$$);
-- (0 rows)cur.execute(
"SELECT full_name FROM inter.students WHERE email = %s",
(email_typed_by_user,), # sent separately as a value, never pasted into the SQL
)- ▸Bind variable = placeholder ($1) whose value is sent separately from the SQL text.
- ▸Benefits: no SQL injection, parsed once with a reusable plan, no quoting problems.
- ▸Never build SQL by concatenating user input.
3.11 Cursors
Life cycle: DECLARE (name the query) → OPEN → FETCH rows (repeat) → CLOSE.
BEGIN;
DECLARE roster CURSOR FOR
SELECT student, course_code FROM inter.v_offering_roster
ORDER BY student, course_code;
FETCH 2 FROM roster; -- Aarav Menon | CS101
-- Aarav Menon | CS201
FETCH NEXT FROM roster; -- Ananya Krishnan | DA301
MOVE FORWARD 1 IN roster; -- skip one row (Diya Nair | CS201)
FETCH ALL FROM roster; -- Diya Nair | DA301
-- Kevin Thomas | CS201
CLOSE roster;
COMMIT;DO $$
DECLARE
cur CURSOR FOR
SELECT full_name FROM inter.students WHERE join_year = 2023 ORDER BY full_name;
v_name TEXT;
BEGIN
OPEN cur;
LOOP
FETCH cur INTO v_name;
EXIT WHEN NOT FOUND; -- no more rows
RAISE NOTICE 'Joined in 2023: %', v_name;
END LOOP;
CLOSE cur;
END $$;
NOTICE: Joined in 2023: Kevin Thomas
NOTICE: Joined in 2023: Rohan PillaiDO $$
DECLARE
rec RECORD;
BEGIN
FOR rec IN SELECT course_code, seats_left FROM inter.v_seat_availability ORDER BY course_code LOOP
RAISE NOTICE '% has % seat(s) left', rec.course_code, rec.seats_left;
END LOOP;
END $$;
NOTICE: CS101 has 39 seat(s) left
NOTICE: CS201 has 0 seat(s) left
NOTICE: DA301 has 0 seat(s) left
NOTICE: MA101 has 30 seat(s) leftPrefer set-based SQL
Use a cursor when you truly need row-by-row work — or to read a huge result in chunks. If one UPDATE or SELECT can do the job, it will be far faster than a loop over a cursor.
- ▸Cursor = a pointer into a query result for row-by-row processing.
- ▸DECLARE → OPEN → FETCH … → CLOSE. FOR rec IN query LOOP does all four automatically.
- ▸In PL/pgSQL, FOUND tells you whether the last FETCH returned a row.
3.12 Views & Materialized Views
| Why use a view | How |
|---|---|
| Simplicity | Write a long join once; everyone queries it as one table |
| Security | Grant SELECT on the view but not on the tables — only chosen columns and rows are visible (Module 1, 1.6) |
| Logical data independence | Tables can change while the view keeps the same shape (Module 1, 1.4) |
| Consistency | A business rule (what counts as “seats left”) is written in one place |
| Command | What it does |
|---|---|
CREATE VIEW v AS SELECT … | Store a query under a name |
CREATE OR REPLACE VIEW v AS SELECT … | Change the query. New columns may be added at the end; existing columns cannot be dropped, renamed or retyped |
DROP VIEW [IF EXISTS] v [CASCADE] | Remove the view (CASCADE also drops views built on it). The base tables are untouched |
CREATE MATERIALIZED VIEW mv AS SELECT … [WITH NO DATA] | Run the query and store the rows (or create it empty) |
REFRESH MATERIALIZED VIEW mv | Run the query again and replace the stored rows |
SELECT dept_code, dept_name, course_id FROM inter.myfirstview ORDER BY course_id;
dept_code | dept_name | course_id
-----------+------------------+-----------
CS | Computer Science | 1
CS | Computer Science | 2
CS | Computer Science | 3
MA | Mathematics | 4
DA | Data Analytics | 5
SELECT pg_get_viewdef('inter.myfirstview', true); -- only the query is stored, no rows
pg_get_viewdef
---------------------------------------------------------
SELECT d.dept_name, +
d.dept_code, +
d.dept_id, +
c.course_id +
FROM inter.courses c +
JOIN inter.departments d ON c.dept_id = d.dept_id;BEGIN;
CREATE VIEW inter.v_course_catalogue AS
SELECT c.course_code, c.title, c.credits, d.dept_name
FROM inter.courses c
LEFT JOIN inter.departments d ON d.dept_id = c.dept_id;
SELECT course_code, title, dept_name FROM inter.v_course_catalogue
WHERE credits = 4 ORDER BY course_code;
course_code | title | dept_name
-------------+-----------------------------+------------------
CS101 | Introduction to Programming | Computer Science
CS201 | Database Systems | Computer Science
DA301 | Data Analytics | Data Analytics
-- add a column at the end: allowed
CREATE OR REPLACE VIEW inter.v_course_catalogue AS
SELECT c.course_code, c.title, c.credits, d.dept_name, c.credits * 15 AS contact_hours
FROM inter.courses c
LEFT JOIN inter.departments d ON d.dept_id = c.dept_id;
-- leave a column out: refused
CREATE OR REPLACE VIEW inter.v_course_catalogue AS
SELECT c.course_code, c.title, d.dept_name
FROM inter.courses c
LEFT JOIN inter.departments d ON d.dept_id = c.dept_id;
ERROR: cannot drop columns from view <- DROP VIEW, then CREATE VIEW instead
ROLLBACK;BEGIN;
CREATE VIEW inter.v_cs_only AS SELECT * FROM inter.myfirstview WHERE dept_code = 'CS';
DROP VIEW inter.myfirstview;
ERROR: cannot drop view inter.myfirstview because other objects depend on it
DETAIL: view inter.v_cs_only depends on view inter.myfirstview
HINT: Use DROP ... CASCADE to drop the dependent objects too.
ROLLBACK;Simple and complex views; updating through a view
| Simple view | Complex view | |
|---|---|---|
| Built on | One table | Several tables (joins), or one table with grouping |
| Contains | Only columns and a WHERE | May use joins, GROUP BY, aggregates, DISTINCT, UNION |
| INSERT / UPDATE / DELETE through it | Yes — automatically updatable | No — unless an INSTEAD OF trigger (3.15) says what to do |
| In university_lab | A view of the CS courses only | myfirstview, v_offering_roster, v_seat_availability |
A row changed through an updatable view may no longer match the view's WHERE — it would silently “disappear” from the view. WITH CHECK OPTION refuses such changes.
BEGIN;
CREATE VIEW inter.v_cs_courses AS
SELECT course_id, course_code, title, credits, dept_id
FROM inter.courses
WHERE dept_id = (SELECT dept_id FROM inter.departments WHERE dept_code = 'CS')
WITH CHECK OPTION;
UPDATE inter.v_cs_courses SET credits = 4 WHERE course_code = 'CS210';
UPDATE 1 <- the change goes through to inter.courses
INSERT INTO inter.v_cs_courses (course_code, title, credits, dept_id)
VALUES ('MA999', 'Not a CS course', 3, (SELECT dept_id FROM inter.departments WHERE dept_code = 'MA'));
ERROR: new row violates check option for view "v_cs_courses"
DETAIL: Failing row contains (…, MA999, Not a CS course, 3, 2).
ROLLBACK;BEGIN;
CREATE VIEW inter.v_enrollment_entry AS
SELECT s.email AS student_email, c.course_code, sem.name AS semester
FROM inter.enrollments e
JOIN inter.students s ON s.student_id = e.student_id
JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters sem ON sem.semester_id = o.semester_id;
INSERT INTO inter.v_enrollment_entry VALUES ('rohan@duk.ac.in', 'MA101', '2024-Even');
ERROR: cannot insert into view "v_enrollment_entry"
DETAIL: Views that do not select from a single table or view are not automatically updatable.
HINT: To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.
ROLLBACK;Materialized views
mymaterializedview stores the same query as myfirstview. It was created WITH NO DATA, so it holds no rows until its first refresh:
SELECT * FROM inter.mymaterializedview;
ERROR: materialized view "mymaterializedview" has not been populated
HINT: Use the REFRESH MATERIALIZED VIEW command.
REFRESH MATERIALIZED VIEW inter.mymaterializedview;
SELECT dept_code, dept_name, course_id FROM inter.mymaterializedview ORDER BY course_id;
dept_code | dept_name | course_id
-----------+------------------+-----------
CS | Computer Science | 1
CS | Computer Science | 2
CS | Computer Science | 3
MA | Mathematics | 4
DA | Data Analytics | 5BEGIN;
UPDATE inter.departments SET dept_name = 'Computer Science & Engineering' WHERE dept_code = 'CS';
SELECT (SELECT DISTINCT dept_name FROM inter.myfirstview WHERE dept_code = 'CS') AS live_view,
(SELECT DISTINCT dept_name FROM inter.mymaterializedview WHERE dept_code = 'CS') AS materialized;
live_view | materialized
--------------------------------+------------------
Computer Science & Engineering | Computer Science <- stale until the next REFRESH
REFRESH MATERIALIZED VIEW inter.mymaterializedview;
SELECT DISTINCT dept_name FROM inter.mymaterializedview WHERE dept_code = 'CS';
-- Computer Science & Engineering
ROLLBACK;| View | Materialized view | |
|---|---|---|
| Stores | Only the query | The query and its result rows |
| Data is | Always current | As of the last REFRESH |
| Reading it | Runs the query every time | Fast — reads stored rows; can be indexed |
| Takes space | No | Yes |
| Good for | Simplifying queries, security, independence | Slow reports and dashboards that may be a little out of date |
- ▸View = a stored SELECT used like a table (virtual table); it stores no data.
- ▸Simple (one-table) views are updatable; WITH CHECK OPTION stops changes that would leave the view.
- ▸Complex views (joins, GROUP BY) need an INSTEAD OF trigger to accept INSERT / UPDATE / DELETE.
- ▸Materialized view = stored result; fast to read, stale until REFRESH MATERIALIZED VIEW.
3.13 Functions
| Kind | Examples |
|---|---|
| Aggregate | COUNT, SUM, AVG, MIN, MAX — one result from many rows (see 3.6) |
| String | upper, lower, length, left, substring, split_part, trim, replace, || |
| Numeric | round, ceil, floor, abs, mod, power |
| Date and time | now(), current_date, extract, date_trunc, age, to_char |
| Conversion | CAST(x AS type), x::type, to_char, to_date, to_number |
| NULL handling | COALESCE (first non-NULL), NULLIF (NULL if equal) |
SELECT upper(full_name) AS upper_name, length(full_name) AS letters,
split_part(email, '@', 1) AS username, left(full_name, 1) || '.' AS initial
FROM inter.students WHERE join_year = 2023 ORDER BY 1;
upper_name | letters | username | initial
--------------+---------+----------+---------
KEVIN THOMAS | 12 | kevin | K.
ROHAN PILLAI | 12 | rohan | R.SELECT name, end_date - start_date AS days,
to_char(start_date, 'DD Mon YYYY') AS starts,
extract(month FROM start_date) AS start_month
FROM inter.semesters ORDER BY start_date;
name | days | starts | start_month
-----------+------+-------------+-------------
2024-Odd | 152 | 01 Jul 2024 | 7
2024-Even | 133 | 02 Jan 2025 | 1
SELECT round(2 / 3.0, 2), ceil(4.1), floor(4.9), mod(17, 5), power(2, 10),
CAST('2024' AS integer) + 1, COALESCE(NULL, 'no value');
-- 0.67 | 5 | 4 | 2 | 1024 | 2025 | no valueCREATE OR REPLACE FUNCTION inter.fn_seats_left(p_offering_id INTEGER)
RETURNS INTEGER
LANGUAGE sql STABLE
AS $$
SELECT o.capacity - COUNT(e.enrollment_id)::int
FROM inter.course_offerings o
LEFT JOIN inter.enrollments e ON e.offering_id = o.offering_id
WHERE o.offering_id = p_offering_id
GROUP BY o.capacity;
$$;
SELECT c.course_code, inter.fn_seats_left(o.offering_id) AS seats_left
FROM inter.course_offerings o JOIN inter.courses c USING (course_id)
ORDER BY 1;
course_code | seats_left
-------------+------------
CS101 | 39
CS201 | 0
DA301 | 0
MA101 | 30CREATE OR REPLACE FUNCTION inter.fn_student_load(p_email TEXT)
RETURNS TEXT
LANGUAGE plpgsql
AS $$
DECLARE
v_student INTEGER;
v_courses INTEGER;
BEGIN
SELECT student_id INTO v_student FROM inter.students WHERE email = p_email;
IF v_student IS NULL THEN
RAISE EXCEPTION 'No student with email %', p_email;
END IF;
SELECT COUNT(*) INTO v_courses FROM inter.enrollments WHERE student_id = v_student;
IF v_courses = 0 THEN
RETURN 'not enrolled';
ELSIF v_courses = 1 THEN
RETURN '1 course';
ELSE
RETURN v_courses || ' courses';
END IF;
END;
$$;
SELECT full_name, inter.fn_student_load(email) AS load FROM inter.students ORDER BY full_name;
full_name | load
-----------------+--------------
Aarav Menon | 2 courses
Ananya Krishnan | 1 course
Diya Nair | 2 courses
Fatima Rahman | not enrolled
Kevin Thomas | 1 course
Rohan Pillai | not enrolled
SELECT inter.fn_student_load('nobody@duk.ac.in');
ERROR: No student with email nobody@duk.ac.in
-- tidy up
DROP FUNCTION inter.fn_student_load;
DROP FUNCTION inter.fn_seats_left;- ▸A function always returns a value and can be used inside SELECT, WHERE and other expressions.
- ▸LANGUAGE sql for a single query; LANGUAGE plpgsql for variables, IF, loops and errors.
- ▸The body sits between $$ … $$ (dollar quoting), so quotes inside need no escaping.
3.14 Stored Procedures
CALL, does not return a value the way a function does (though it can pass values back through OUT parameters), and — unlike a function — may COMMIT or ROLLBACK inside its body.| Parameter mode | Meaning |
|---|---|
| IN (default) | A value passed in; the procedure can read it but not change it |
| OUT | A value passed back out to the caller |
| INOUT | Passed in, may be changed, and passed back out (MySQL calls it IN OUT) |
CREATE OR REPLACE PROCEDURE inter.sp_enroll(p_email TEXT, p_course TEXT, p_semester TEXT)
LANGUAGE plpgsql
AS $$
DECLARE
v_student INTEGER;
v_offering INTEGER;
v_capacity INTEGER;
v_taken INTEGER;
BEGIN
SELECT student_id INTO v_student FROM inter.students WHERE email = p_email;
IF v_student IS NULL THEN
RAISE EXCEPTION 'No student with email %', p_email;
END IF;
SELECT o.offering_id, o.capacity INTO v_offering, v_capacity
FROM inter.course_offerings o
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters s ON s.semester_id = o.semester_id
WHERE c.course_code = p_course AND s.name = p_semester;
IF v_offering IS NULL THEN
RAISE EXCEPTION 'No offering of % in %', p_course, p_semester;
END IF;
SELECT COUNT(*) INTO v_taken FROM inter.enrollments WHERE offering_id = v_offering;
IF v_taken >= v_capacity THEN
RAISE EXCEPTION '% (%) is full: % of % seats taken', p_course, p_semester, v_taken, v_capacity;
END IF;
INSERT INTO inter.enrollments (student_id, offering_id) VALUES (v_student, v_offering);
RAISE NOTICE 'Enrolled % in % (%)', p_email, p_course, p_semester;
END;
$$;BEGIN;
CALL inter.sp_enroll('rohan@duk.ac.in', 'CS101', '2024-Odd');
NOTICE: Enrolled rohan@duk.ac.in in CS101 (2024-Odd)
ROLLBACK; -- keep the sample data unchanged
CALL inter.sp_enroll('fatima@duk.ac.in', 'CS201', '2024-Odd');
ERROR: CS201 (2024-Odd) is full: 3 of 3 seats taken
CALL inter.sp_enroll('fatima@duk.ac.in', 'CS999', '2024-Odd');
ERROR: No offering of CS999 in 2024-OddCREATE OR REPLACE PROCEDURE inter.sp_seat_report(IN p_course TEXT,
OUT p_capacity INTEGER,
OUT p_enrolled INTEGER)
LANGUAGE plpgsql
AS $$
BEGIN
SELECT capacity, enrolled INTO p_capacity, p_enrolled
FROM inter.v_seat_availability WHERE course_code = p_course;
END;
$$;
CALL inter.sp_seat_report('CS201', NULL, NULL);
p_capacity | p_enrolled
------------+------------
3 | 3
-- tidy up
DROP PROCEDURE inter.sp_seat_report;
DROP PROCEDURE inter.sp_enroll;| Function | Procedure | |
|---|---|---|
| Run with | Inside an expression: SELECT fn(…) | CALL sp(…) |
| Returns | Always a value (or a set of rows) | Nothing — but may use OUT / INOUT parameters |
| Use in SELECT / WHERE | Yes | No |
| COMMIT / ROLLBACK inside | No | Yes (when not called inside an outer transaction block) |
| Typical use | Calculations, look-ups, reusable expressions | Business actions: enroll, register, process a batch |
- ▸Procedure = an action, run with CALL. Function = returns a value, used in queries.
- ▸Parameter modes: IN, OUT, INOUT.
- ▸Checks inside a procedure plus constraints in the tables keep the data valid.
3.15 Triggers
INSERT, UPDATE, DELETE or TRUNCATE — happens on a table or view. Nobody calls it: the event fires it. In PostgreSQL a trigger has two parts: a trigger function (RETURNS trigger) and the CREATE TRIGGER statement that attaches it to a table.A trigger is an Event–Condition–Action (ECA) rule: when an event happens, if a condition holds, do an action. A database with such rules is called an active database — it reacts on its own instead of only doing what it is told.
CREATE TRIGGER trigger_name
{ BEFORE | AFTER | INSTEAD OF } -- timing
{ INSERT | UPDATE [OF column, …] | DELETE | TRUNCATE } [OR …] -- event(s)
ON table_or_view
[ FOR EACH ROW | FOR EACH STATEMENT ] -- level (default: statement)
[ WHEN (condition) ] -- optional condition
EXECUTE FUNCTION trigger_function(); -- action| Timing | Runs | Typical use |
|---|---|---|
| BEFORE | Before the row is written | Check or correct the new row; RETURN NEW to go ahead, RAISE EXCEPTION to stop |
| AFTER | After the row is written | React to a change that has happened: audit logs, totals, notifications |
| INSTEAD OF | In place of the change (views only) | Make a complex view accept INSERT / UPDATE / DELETE |
| Inside the trigger function | Meaning |
|---|---|
NEW | The new row — in INSERT and UPDATE row triggers |
OLD | The old row — in UPDATE and DELETE row triggers |
TG_OP | The event: 'INSERT', 'UPDATE', 'DELETE' or 'TRUNCATE' |
TG_WHEN, TG_LEVEL, TG_TABLE_NAME | BEFORE / AFTER / INSTEAD OF; ROW / STATEMENT; the table that fired it |
| Return value | BEFORE row trigger: the row to write (NEW), or NULL to skip the row. AFTER and statement triggers: ignored — RETURN NULL |
BEGIN;
CREATE FUNCTION inter.fn_check_capacity() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT COUNT(*) FROM inter.enrollments WHERE offering_id = NEW.offering_id) -- condition
>= (SELECT capacity FROM inter.course_offerings WHERE offering_id = NEW.offering_id) THEN
RAISE EXCEPTION 'Offering % is full', NEW.offering_id; -- action
END IF;
RETURN NEW; -- go ahead and insert the row
END;
$$;
CREATE TRIGGER trg_check_capacity
BEFORE INSERT ON inter.enrollments -- event
FOR EACH ROW EXECUTE FUNCTION inter.fn_check_capacity();
-- CS101 has 39 seats left: accepted
INSERT INTO inter.enrollments (student_id, offering_id)
SELECT s.student_id, o.offering_id
FROM inter.students s, inter.course_offerings o JOIN inter.courses c ON c.course_id = o.course_id
WHERE s.email = 'fatima@duk.ac.in' AND c.course_code = 'CS101';
INSERT 0 1
-- CS201 is full (3 of 3): refused by the trigger
INSERT INTO inter.enrollments (student_id, offering_id)
SELECT s.student_id, o.offering_id
FROM inter.students s, inter.course_offerings o JOIN inter.courses c ON c.course_id = o.course_id
WHERE s.email = 'fatima@duk.ac.in' AND c.course_code = 'CS201';
ERROR: Offering 1 is full
CONTEXT: PL/pgSQL function inter.fn_check_capacity() line 5 at RAISE
ROLLBACK; -- the trigger, its function and the CS101 row all disappearThe stored procedure sp_enroll in 3.14 makes the same check — but only for enrollments made through the procedure. The trigger guards every INSERT, however it is written.
BEGIN;
CREATE FUNCTION inter.fn_tidy_email() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.email := lower(trim(NEW.email)); -- change the row before it is written
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_tidy_email
BEFORE INSERT OR UPDATE OF email ON inter.students
FOR EACH ROW EXECUTE FUNCTION inter.fn_tidy_email();
UPDATE inter.students SET email = ' Rohan.P@DUK.AC.IN ' WHERE full_name = 'Rohan Pillai';
SELECT full_name, email FROM inter.students WHERE full_name = 'Rohan Pillai';
full_name | email
--------------+-------------------
Rohan Pillai | rohan.p@duk.ac.in
ROLLBACK;BEGIN;
CREATE TABLE inter.enrollment_log (
logged_at TIMESTAMPTZ NOT NULL DEFAULT now(),
action TEXT NOT NULL,
student_id INTEGER NOT NULL,
offering_id INTEGER NOT NULL
);
CREATE FUNCTION inter.fn_log_enrollment() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO inter.enrollment_log (action, student_id, offering_id)
VALUES ('INSERT', NEW.student_id, NEW.offering_id);
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO inter.enrollment_log (action, student_id, offering_id)
VALUES ('DELETE', OLD.student_id, OLD.offering_id);
END IF;
RETURN NULL; -- ignored for AFTER triggers
END;
$$;
CREATE TRIGGER trg_log_enrollment
AFTER INSERT OR DELETE ON inter.enrollments
FOR EACH ROW EXECUTE FUNCTION inter.fn_log_enrollment();
INSERT INTO inter.enrollments (student_id, offering_id)
SELECT s.student_id, o.offering_id
FROM inter.students s, inter.course_offerings o JOIN inter.courses c ON c.course_id = o.course_id
WHERE s.email = 'rohan@duk.ac.in' AND c.course_code = 'CS101';
DELETE FROM inter.enrollments
WHERE student_id = (SELECT student_id FROM inter.students WHERE email = 'kevin@duk.ac.in');
SELECT l.action, s.full_name, c.course_code
FROM inter.enrollment_log l
JOIN inter.students s USING (student_id)
JOIN inter.course_offerings o USING (offering_id)
JOIN inter.courses c ON c.course_id = o.course_id
ORDER BY l.action DESC, s.full_name;
action | full_name | course_code
--------+--------------+-------------
INSERT | Rohan Pillai | CS101
DELETE | Kevin Thomas | CS201
ROLLBACK;Row-level and statement-level triggers
A row-level trigger (FOR EACH ROW) fires once for every row the statement changes, and can see NEW and OLD. A statement-level trigger (FOR EACH STATEMENT, the default) fires once per statement — even if no row changes.
BEGIN;
CREATE FUNCTION inter.fn_say() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE '% trigger fired for %', TG_LEVEL, TG_OP;
RETURN NULL;
END;
$$;
CREATE TRIGGER trg_each_row AFTER UPDATE ON inter.courses
FOR EACH ROW EXECUTE FUNCTION inter.fn_say();
CREATE TRIGGER trg_each_statement AFTER UPDATE ON inter.courses
FOR EACH STATEMENT EXECUTE FUNCTION inter.fn_say();
UPDATE inter.courses SET credits = credits WHERE course_code LIKE 'CS%';
NOTICE: ROW trigger fired for UPDATE
NOTICE: ROW trigger fired for UPDATE
NOTICE: ROW trigger fired for UPDATE
NOTICE: STATEMENT trigger fired for UPDATE
UPDATE 3
UPDATE inter.courses SET credits = credits WHERE course_code = 'XX000';
NOTICE: STATEMENT trigger fired for UPDATE
UPDATE 0 <- no rows, but the statement still ran
ROLLBACK;INSTEAD OF triggers: making a view accept changes
In 3.12, PostgreSQL refused an INSERT into the join view v_enrollment_entry and suggested an INSTEAD OF trigger. The trigger tells the database what an INSERT into the view should mean: look up the ids and insert into the real table.
BEGIN;
CREATE VIEW inter.v_enrollment_entry AS
SELECT s.email AS student_email, c.course_code, sem.name AS semester
FROM inter.enrollments e
JOIN inter.students s ON s.student_id = e.student_id
JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters sem ON sem.semester_id = o.semester_id;
CREATE FUNCTION inter.fn_enrollment_entry() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO inter.enrollments (student_id, offering_id)
SELECT s.student_id, o.offering_id
FROM inter.students s, inter.course_offerings o
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters sem ON sem.semester_id = o.semester_id
WHERE s.email = NEW.student_email AND c.course_code = NEW.course_code AND sem.name = NEW.semester;
IF NOT FOUND THEN
RAISE EXCEPTION 'No student % or no offering of % in %', NEW.student_email, NEW.course_code, NEW.semester;
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_enrollment_entry
INSTEAD OF INSERT ON inter.v_enrollment_entry
FOR EACH ROW EXECUTE FUNCTION inter.fn_enrollment_entry();
INSERT INTO inter.v_enrollment_entry VALUES ('rohan@duk.ac.in', 'MA101', '2024-Even');
INSERT 0 1 <- accepted this time
SELECT * FROM inter.v_enrollment_entry WHERE student_email = 'rohan@duk.ac.in';
student_email | course_code | semester
-----------------+-------------+-----------
rohan@duk.ac.in | MA101 | 2024-Even
SELECT event_object_table, trigger_name, action_timing, event_manipulation, action_orientation
FROM information_schema.triggers WHERE trigger_schema = 'inter';
event_object_table | trigger_name | action_timing | event_manipulation | action_orientation
--------------------+----------------------+---------------+--------------------+--------------------
v_enrollment_entry | trg_enrollment_entry | INSTEAD OF | INSERT | ROW
ROLLBACK;| Managing triggers | Command |
|---|---|
| List the triggers of a schema | SELECT … FROM information_schema.triggers |
| Switch one off for a while, and back on | ALTER TABLE t DISABLE TRIGGER name; … ENABLE TRIGGER name; |
| Remove it | DROP TRIGGER name ON t; |
| Trigger | Stored procedure | Function | |
|---|---|---|---|
| Runs | Automatically, on an event | When called: CALL sp(…) | When used in a query: SELECT fn(…) |
| Parameters | None — it sees NEW, OLD and TG_OP | IN, OUT, INOUT | IN (returns a value) |
| Typical use | Rules that must hold for every change; auditing | Business actions | Calculations and look-ups |
Use a constraint when a constraint can do it
Triggers are invisible to whoever writes the INSERT, they slow down every change to the table, and one trigger can fire another. If a NOT NULL, UNIQUE, CHECK or FOREIGN KEY constraint can express the rule, use the constraint. Use a trigger for rules that look at other rows or tables — like the capacity check — and for logging.
- ▸Trigger = code run automatically on INSERT / UPDATE / DELETE / TRUNCATE — an Event–Condition–Action rule.
- ▸Timing: BEFORE (check or change the row), AFTER (react, e.g. audit), INSTEAD OF (views).
- ▸Level: FOR EACH ROW (once per row; NEW / OLD) or FOR EACH STATEMENT (once per statement).
- ▸In PostgreSQL: CREATE FUNCTION … RETURNS trigger, then CREATE TRIGGER … EXECUTE FUNCTION.
Module 3 at a glance
| Topic | One-line answer |
|---|---|
| SQL | Declarative, set-based, standard language for relational databases. |
| Data types | Numbers, exact decimals, text, dates, boolean, and more; types enforce the domain. |
| Operators | Arithmetic, comparison, logical, BETWEEN / IN / LIKE / IS NULL / EXISTS; NULL means unknown. |
| Commands | DDL (structure), DQL (SELECT), DML (rows), DCL (privileges), TCL (transactions). |
| Parsing | Parse → analyse → rewrite → plan → execute; logical order FROM … LIMIT. |
| Querying | WHERE filters rows; GROUP BY + aggregates summarise; HAVING filters groups. |
| Joins | INNER, LEFT, RIGHT, FULL, CROSS, self. |
| Sub-queries | Non-correlated run once; correlated refer to the outer row. |
| Hierarchical | WITH RECURSIVE: anchor UNION ALL recursive step. |
| Bind variables | Placeholders like $1: safe from injection, parsed once, plan reusable. |
| Cursors | Row-by-row access: DECLARE, OPEN, FETCH, CLOSE. |
| Views | A stored SELECT used like a table; simple views are updatable; materialized views store rows until REFRESH. |
| Functions vs procedures | Function returns a value (used in SELECT); procedure performs an action (CALL). |
| Triggers | Code fired automatically by INSERT / UPDATE / DELETE: BEFORE, AFTER or INSTEAD OF; per row or per statement. |
Practice on university_lab
Filter and sort
EasyJoin and count
MediumCorrelated sub-query
MediumRecursive query, the other way round
HardWrite a function
HardA view of each student's load
MediumA trigger that tidies course codes
HardExam-style questions
- List four features of SQL.
- Differentiate DELETE, TRUNCATE and DROP.
- What is a correlated sub-query?
- What is a bind variable? Give one advantage.
- What is a cursor?
- Differentiate WHERE and HAVING.
- What is a view? Differentiate a view and a materialized view.
- What is a trigger? Differentiate BEFORE and AFTER triggers.
- Explain the types of SQL commands with examples.
- Explain the types of joins with examples.
- Explain how an SQL statement is parsed and executed.
- Explain hierarchical queries with an example.
- Compare functions and stored procedures, with an example of each.
- Explain views: creating, updating through a view, WITH CHECK OPTION and materialized views.
- Explain triggers with examples: timing, row-level and statement-level, NEW and OLD.
- Explain SQL operators, including how NULL is handled.
