Digital University Kerala

SQL Lab Notes

PostgreSQL for Data Analytics

Course Instructor:Dr. Ajith Kumar
Academic Year: 2026-2028
Class Notes/Module 3
Module 3 · CO3 · Lecture notes: Module III · Labs 1, 3, 4

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.

🎯 After this module you can
  • ▸ 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
🏫 Examples use

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.

Set up the database first →

3.1 Introduction to SQL & Its Features

📖 Definition · SQL
Structured Query Language — the standard language for defining, querying, changing and controlling data in a relational database. It was created at IBM in the 1970s (as SEQUEL) for Codd's relational model and is an ANSI/ISO standard used by every RDBMS.
FeatureWhat it means
DeclarativeYou say WHAT data you want, not HOW to find it. The database decides how.
Set-basedOne statement works on many rows at once.
CompleteOne language defines structure (DDL), changes data (DML), controls access (DCL) and manages transactions (TCL).
Standard and portableThe core is the same in PostgreSQL, Oracle, MySQL and SQL Server; each adds its own extensions.
English-likeStatements read almost like sentences: SELECT … FROM … WHERE …
EmbeddableUsed from Python, Java and other languages, and inside the database in functions and procedures.
🏫 Example · declarative: say what, not how
Which students joined in 2024?sql
SELECT full_name
FROM inter.students
WHERE join_year = 2024
ORDER BY full_name;

    full_name
-----------------
 Aarav Menon
 Ananya Krishnan
 Diya Nair
 Fatima Rahman

Nothing here says which file to open, whether to use an index, or how to sort. The database works that out (see 3.5).

✅ Remember
  • ▸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

📖 Definition
A data type fixes the kind of values a column can hold, how much space they take, how they are compared and sorted, and which operations work on them. Choosing the right type is the first line of domain integrity (Module 2, 2.8).
CategoryPostgreSQLMySQL name (Module III)Use for
Whole numberssmallint · integer · bigintTINYINT, SMALLINT · MEDIUMINT, INT · BIGINTCounts, years, ids
Exact decimalsnumeric(p,s) / decimal(p,s)DECIMALMoney, marks, GPA
Approximate decimalsreal · double precisionFLOAT · DOUBLEScientific measurements
Auto-numberingserial, or integer GENERATED AS IDENTITYAUTO_INCREMENTSurrogate primary keys
Textchar(n) · varchar(n) · textCHAR · VARCHAR · TINYTEXT … LONGTEXTCodes, names, long text
BinarybyteaBINARY, VARBINARY, BLOB familyFiles, images
Date and timedate · time · timestamp · timestamptz · intervalDATE · TIME · DATETIME · TIMESTAMP · (none)Dates, moments, durations
Yes / nobooleanBOOLEAN (stored as TINYINT(1))Flags
Fixed list of valuesCREATE TYPE … AS ENUM, or a CHECKENUM · SETStatus codes
Modern extrasuuid · jsonb · arrays (text[])JSONUnique ids, documents, lists
🏫 Example · types decide how values behave
Ask PostgreSQL for the type of a valuesql
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 | boolean
The same operator gives different results for different typessql
SELECT 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
✅ Remember
  • ▸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

📖 Definition
An operator is a symbol or keyword that performs an operation — arithmetic, comparison or logic — mostly inside the WHERE clause to build conditions.
KindOperatorsExample on university_lab
Arithmetic+ − * / % (modulus) ^ (power)credits * 15
Comparison= <> != < > <= >=credits >= 4
LogicalAND OR NOTcredits >= 4 AND course_code LIKE 'CS%'
RangeBETWEEN a AND b (inclusive)join_year BETWEEN 2023 AND 2024
ListIN (…) NOT IN (…)course_code IN ('CS101', 'MA101')
PatternLIKE (case-sensitive) · ILIKE (PostgreSQL, case-insensitive); % = any text, _ = one characteremail LIKE 'a%'
NULL testIS NULL IS NOT NULLfaculty_id IS NULL
Sub-queryEXISTS · ANY / SOME · ALLcredits > ALL (SELECT …)
Text|| (concatenate)full_name || ' <' || email || '>'
🏫 Example · operators at work
Arithmetic in the SELECT list — contact hours at 15 per creditsql
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 |            45
Comparison, logical, pattern and ALLsql
SELECT 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, DA301
NULL means unknown — three-valued logicsql
SELECT TRUE AND NULL, FALSE AND NULL, TRUE OR NULL, NOT NULL::boolean;

 ?column? | ?column? | ?column? | ?column?
----------+----------+----------+----------
          | f        | t        |              <- NULL, false, true, NULL

Not 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.

✅ Remember
  • ▸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

📖 Definition
SQL statements fall into families by purpose: DDL defines structure, DML works with the data, DCL controls access, and TCL manages transactions. Some books list SELECT separately as DQL (data query language).
FamilyCommandsPurpose
DDL — Data DefinitionCREATE · ALTER · DROP · TRUNCATE · COMMENT · ALTER … RENAMECreate, change and remove database objects
DQL — Data QuerySELECTRead data
DML — Data ManipulationINSERT · UPDATE · DELETE · MERGEAdd, change and remove rows
DCL — Data ControlGRANT · REVOKEGive and take back privileges
TCL — Transaction ControlBEGIN · COMMIT · ROLLBACK · SAVEPOINT · ROLLBACK TO · SET TRANSACTIONGroup 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.

🏫 Example · one example per family
DDL — create, alter, rename and comment… then roll it all backsql
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 existed
TRUNCATE is transactional toosql
BEGIN;
TRUNCATE inter.enrollments;
SELECT COUNT(*) FROM inter.enrollments;   -- 0
ROLLBACK;
SELECT COUNT(*) FROM inter.enrollments;   -- 6 — all back
DML — upsert with ON CONFLICT, and MERGEsql
BEGIN;
-- 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;
DCL — see Module 1, 1.6 for a full examplesql
GRANT  SELECT ON inter.v_offering_roster TO faculty_reader;
REVOKE SELECT ON inter.v_offering_roster FROM faculty_reader;
TCL — a SAVEPOINT undoes part of a transactionsql
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
DELETETRUNCATEDROP
FamilyDMLDDLDDL
RemovesChosen rows (WHERE), or allAll rowsThe whole table: rows and structure
Speed on big tablesSlower — row by rowVery fastVery fast
Fires row triggersYesNoNo
Rollback in PostgreSQLYesYesYes

MySQL (Module III) → PostgreSQL

TaskMySQLPostgreSQL
List databasesSHOW DATABASES;\l in psql, or SELECT datname FROM pg_database;
Switch databaseUSE university_lab;\c university_lab
Create a databaseCREATE DATABASE IF NOT EXISTS db;CREATE DATABASE db; (no IF NOT EXISTS)
List / describe tablesSHOW TABLES; DESCRIBE students;\dt inter.* \d inter.students
Auto-numbering idid INT AUTO_INCREMENTid SERIAL or id INTEGER GENERATED ALWAYS AS IDENTITY
Quote a name`my table`"my table"
Change a columnALTER 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 positionADD COLUMN c … AFTER bNot supported — new columns are added last
Name a foreign keyFOREIGN KEY fk_cat (cat_id) REFERENCES …CONSTRAINT fk_cat FOREIGN KEY (cat_id) REFERENCES …
Index on a foreign keyCreated automaticallyNot automatic — create it: CREATE INDEX ON t (cat_id);
UpsertINSERT … ON DUPLICATE KEY UPDATEINSERT … ON CONFLICT … DO UPDATE or MERGE
Limit a DELETEDELETE … LIMIT 10Not supported — use WHERE id IN (SELECT … LIMIT 10)
✅ Remember
  • ▸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

📖 Definition
Before any data is read, the DBMS turns the SQL text into an executable plan. The statement is parsed (syntax), analysed (meaning, against the catalog), rewritten (views expanded), planned (the cheapest way chosen) and finally executed.
1 · Parser
Checks syntax against the SQL grammar; builds a parse tree.
2 · Analyser
Semantic check: do the tables and columns exist? Is any name ambiguous? Do the types fit?
3 · Rewriter
Replaces each view with the query behind it.
4 · Planner
Picks the cheapest plan: scans, indexes, join order and method.
5 · Executor
Checks privileges, runs the plan, returns the rows.
Figure 3.1 — The life of a query in PostgreSQL
🏫 Example · each stage has its own errors
Parser — syntaxsql
SELEC * FROM inter.students;
ERROR:  syntax error at or near "SELEC"
Analyser — semantics: objects must exist, names must be clearsql
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_id
Planner — EXPLAIN shows the plan it chose (your costs will differ)sql
EXPLAIN
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:

1. FROM / JOIN2. WHERE3. GROUP BY4. HAVING5. SELECT6. DISTINCT7. ORDER BY8. LIMIT / OFFSET
Figure 3.2 — Logical processing order of a SELECT statement
Why a column alias works in ORDER BY but not in WHEREsql
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
✅ Remember
  • ▸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

📖 Definition
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).
The full shape of a SELECT (every clause after SELECT … FROM is optional)sql
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;
🏫 Example · from simple to summarised
DISTINCT, ORDER BY and LIMITsql
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       |       30
CASE — an if-then-else inside a querysql
SELECT 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 | OPEN
Aggregate functions summarise many rows into onesql
SELECT 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.60
GROUP BY makes one summary row per group; HAVING filters the groupssql
SELECT 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 | 4

Set 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).

Courses that are offered AND are a prerequisite for somethingsql
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
✅ Remember
  • ▸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

📖 Definition
A join combines rows from two or more tables by matching related columns — usually a foreign key with the primary key it refers to. It rebuilds the information that normalization split into separate tables.
JoinReturns
INNER JOINOnly rows that match in both tables
LEFT [OUTER] JOINAll rows of the left table, with matches from the right (NULLs where there is none)
RIGHT [OUTER] JOINAll rows of the right table, with matches from the left
FULL [OUTER] JOINAll rows of both, matched where possible
LEFT JOIN … WHERE right.key IS NULLRows of the left table with no match at all
CROSS JOINEvery combination of rows (Cartesian product)
Self joinA table joined to itself, using two aliases
🏫 Example · every kind of join on the inter schema
INNER JOIN — who teaches what, and whensql
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-Odd
LEFT JOIN — every student, even those with no enrollmentsql
SELECT 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    |       0
RIGHT JOIN + IS NULL — offerings nobody has enrolled insql
SELECT 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-Even
FULL JOIN — compare two lists: offered in 2024-Odd vs needed as a prerequisitesql
SELECT 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
CROSS JOIN and SELF JOINsql
-- 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 Rahman

Shortcut: 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.

✅ Remember
  • ▸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

📖 Definition · Sub-query
A query nested inside another statement — in WHERE, FROM or the SELECT list. A non-correlated sub-query is independent: it could run on its own, and conceptually runs once.
📖 Definition · Correlated sub-query
A sub-query that refers to a column of the outer query. It cannot run on its own; conceptually it is evaluated again for each row of the outer query.
🏫 Example · non-correlated vs correlated
Non-correlated — the inner query runs once, and its answer is used everywheresql
SELECT full_name FROM inter.students
WHERE dept_id = (SELECT dept_id FROM inter.departments WHERE dept_code = 'DA');
-- Ananya Krishnan, Diya Nair
Correlated, in the SELECT list — a count for each studentsql
SELECT 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
Correlated, with EXISTS and NOT EXISTSsql
-- 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 Pillai
Correlated comparison — the earliest joiners in each departmentsql
SELECT 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    |      2023
Correlated — offerings that are fullsql
SELECT 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 | 2

Performance

“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.

✅ Remember
  • ▸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

📖 Definition
A hierarchical query walks data that refers to itself — a tree or chain such as an organisation chart, a folder tree, or course prerequisites. Oracle uses 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.
🏫 Example · the prerequisite chain behind DA301

DA301 needs CS201, and CS201 needs CS101 and CS210. One recursive query finds the whole chain, level by level:

WITH RECURSIVE — every course you must pass before DA301sql
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 → CS210
The same tree in Oracle (for comparison — does not run in PostgreSQL)sql
SELECT 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.

✅ Remember
  • ▸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

📖 Definition
A bind variable (or parameter) is a placeholder in a SQL statement — $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.
🏫 Example · PREPARE and EXECUTE
A prepared statement with one bind variable, $1sql
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;
psql 16+ can bind a value to any querysql
SELECT full_name FROM inter.students WHERE email = $1 \bind 'ananya@duk.ac.in' \g
-- Ananya Krishnan
Why it matters: SQL injectionsql
-- 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)
The same idea from an application (Python, psycopg)python
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
)
✅ Remember
  • ▸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

📖 Definition
A cursor is a pointer into the result of a query that lets a program read the rows a few at a time instead of all at once. SQL works on whole sets; a cursor is how procedural code steps through a set row by row.

Life cycle: DECLARE (name the query) → OPEN → FETCH rows (repeat) → CLOSE.

🏫 Example · a cursor in plain SQL
SQL cursors live inside a transactionsql
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;
🏫 Example · cursors in PL/pgSQL
Explicit cursor: OPEN, FETCH in a loop, CLOSEsql
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 Pillai
Implicit cursor: FOR … IN query LOOP opens, fetches and closes for yousql
DO $$
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) left

Prefer 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.

✅ Remember
  • ▸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

📖 Definition · View
A view is a named, stored SELECT query that can be used like a table — a virtual table. It stores no rows: every time you query the view, the database runs its query against the current base tables.
📖 Definition · Materialized view
A view whose result is stored on disk like a table. Reading it is fast, but the stored rows do not follow changes to the base tables until you refresh it.
Why use a viewHow
SimplicityWrite a long join once; everyone queries it as one table
SecurityGrant SELECT on the view but not on the tables — only chosen columns and rows are visible (Module 1, 1.6)
Logical data independenceTables can change while the view keeps the same shape (Module 1, 1.4)
ConsistencyA business rule (what counts as “seats left”) is written in one place
CommandWhat 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 mvRun the query again and replace the stored rows
🏫 Example · the view you created in class
Query a view like a table — and see the query it storessql
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;
🏫 Example · create, change and drop a view
Inside a transaction, so nothing is left behindsql
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;
A view that other views depend on cannot simply be droppedsql
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 viewComplex view
Built onOne tableSeveral tables (joins), or one table with grouping
ContainsOnly columns and a WHEREMay use joins, GROUP BY, aggregates, DISTINCT, UNION
INSERT / UPDATE / DELETE through itYes — automatically updatableNo — unless an INSTEAD OF trigger (3.15) says what to do
In university_labA view of the CS courses onlymyfirstview, 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.

🏫 Example · an updatable view WITH CHECK OPTION
CS courses only — and only CS courses may be written through itsql
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;
A join view is not updatable — PostgreSQL even suggests the fixsql
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

🏫 Example · the materialized view you created in class

mymaterializedview stores the same query as myfirstview. It was created WITH NO DATA, so it holds no rows until its first refresh:

Empty until refreshedsql
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   |         5
A view is always current; a materialized view is current as of its last refreshsql
BEGIN;
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;
ViewMaterialized view
StoresOnly the queryThe query and its result rows
Data isAlways currentAs of the last REFRESH
Reading itRuns the query every timeFast — reads stored rows; can be indexed
Takes spaceNoYes
Good forSimplifying queries, security, independenceSlow reports and dashboards that may be a little out of date
✅ Remember
  • ▸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

📖 Definition
A function takes zero or more inputs and returns a value, so it can be used inside any SQL expression. PostgreSQL has hundreds of built-in functions, and you can write your own user-defined functions in SQL or PL/pgSQL.
KindExamples
AggregateCOUNT, SUM, AVG, MIN, MAX — one result from many rows (see 3.6)
Stringupper, lower, length, left, substring, split_part, trim, replace, ||
Numericround, ceil, floor, abs, mod, power
Date and timenow(), current_date, extract, date_trunc, age, to_char
ConversionCAST(x AS type), x::type, to_char, to_date, to_number
NULL handlingCOALESCE (first non-NULL), NULLIF (NULL if equal)
🏫 Example · built-in functions
String functionssql
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.
Date, numeric and conversion functionssql
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 value
🏫 Example · user-defined functions
A SQL function — seats left in an offeringsql
CREATE 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       |         30
A PL/pgSQL function — variables, IF / ELSIF and an errorsql
CREATE 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;
✅ Remember
  • ▸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

📖 Definition
A stored procedure is a named program stored in the database that performs an action. It is run with 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 modeMeaning
IN (default)A value passed in; the procedure can read it but not change it
OUTA value passed back out to the caller
INOUTPassed in, may be changed, and passed back out (MySQL calls it IN OUT)
🏫 Example · a procedure that enrolls a student safely
sp_enroll — checks the student, the offering and the seats before insertingsql
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;
$$;
CALL it — one success and two refusalssql
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-Odd
OUT parameters pass values back to the callersql
CREATE 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;
FunctionProcedure
Run withInside an expression: SELECT fn(…)CALL sp(…)
ReturnsAlways a value (or a set of rows)Nothing — but may use OUT / INOUT parameters
Use in SELECT / WHEREYesNo
COMMIT / ROLLBACK insideNoYes (when not called inside an outer transaction block)
Typical useCalculations, look-ups, reusable expressionsBusiness actions: enroll, register, process a batch
✅ Remember
  • ▸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

📖 Definition
A trigger is a database object that runs a piece of code automatically when a given event — 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.

The shape of a triggersql
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
TimingRunsTypical use
BEFOREBefore the row is writtenCheck or correct the new row; RETURN NEW to go ahead, RAISE EXCEPTION to stop
AFTERAfter the row is writtenReact to a change that has happened: audit logs, totals, notifications
INSTEAD OFIn place of the change (views only)Make a complex view accept INSERT / UPDATE / DELETE
Inside the trigger functionMeaning
NEWThe new row — in INSERT and UPDATE row triggers
OLDThe old row — in UPDATE and DELETE row triggers
TG_OPThe event: 'INSERT', 'UPDATE', 'DELETE' or 'TRUNCATE'
TG_WHEN, TG_LEVEL, TG_TABLE_NAMEBEFORE / AFTER / INSTEAD OF; ROW / STATEMENT; the table that fired it
Return valueBEFORE row trigger: the row to write (NEW), or NULL to skip the row. AFTER and statement triggers: ignored — RETURN NULL
🏫 Example · a BEFORE trigger that refuses an enrollment when the class is full
Event: INSERT on enrollments · Condition: no seats left · Action: raise an errorsql
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 disappear

The 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.

🏫 Example · a BEFORE trigger that corrects the new row
Store every email trimmed and in lower casesql
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;
🏫 Example · an AFTER trigger that keeps an audit log
One trigger for two events: TG_OP tells which one fired itsql
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.

🏫 Example · the same UPDATE, both kinds of trigger
Three CS courses updated: three ROW firings, one STATEMENT firingsql
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.

🏫 Example · enroll a student by email, course code and semester
An INSTEAD OF INSERT trigger on a join viewsql
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 triggersCommand
List the triggers of a schemaSELECT … FROM information_schema.triggers
Switch one off for a while, and back onALTER TABLE t DISABLE TRIGGER name; … ENABLE TRIGGER name;
Remove itDROP TRIGGER name ON t;
TriggerStored procedureFunction
RunsAutomatically, on an eventWhen called: CALL sp(…)When used in a query: SELECT fn(…)
ParametersNone — it sees NEW, OLD and TG_OPIN, OUT, INOUTIN (returns a value)
Typical useRules that must hold for every change; auditingBusiness actionsCalculations 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.

✅ Remember
  • ▸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

TopicOne-line answer
SQLDeclarative, set-based, standard language for relational databases.
Data typesNumbers, exact decimals, text, dates, boolean, and more; types enforce the domain.
OperatorsArithmetic, comparison, logical, BETWEEN / IN / LIKE / IS NULL / EXISTS; NULL means unknown.
CommandsDDL (structure), DQL (SELECT), DML (rows), DCL (privileges), TCL (transactions).
ParsingParse → analyse → rewrite → plan → execute; logical order FROM … LIMIT.
QueryingWHERE filters rows; GROUP BY + aggregates summarise; HAVING filters groups.
JoinsINNER, LEFT, RIGHT, FULL, CROSS, self.
Sub-queriesNon-correlated run once; correlated refer to the outer row.
HierarchicalWITH RECURSIVE: anchor UNION ALL recursive step.
Bind variablesPlaceholders like $1: safe from injection, parsed once, plan reusable.
CursorsRow-by-row access: DECLARE, OPEN, FETCH, CLOSE.
ViewsA stored SELECT used like a table; simple views are updatable; materialized views store rows until REFRESH.
Functions vs proceduresFunction returns a value (used in SELECT); procedure performs an action (CALL).
TriggersCode fired automatically by INSERT / UPDATE / DELETE: BEFORE, AFTER or INSTEAD OF; per row or per statement.

Practice on university_lab

1

Filter and sort

Easy
List the code and title of every 4-credit course, ordered by course code.
2

Join and count

Medium
For every faculty member, show how many course offerings they teach — including any who teach none.
3

Correlated sub-query

Medium
Using a correlated sub-query, list the students enrolled in more than one course.
4

Recursive query, the other way round

Hard
List every course that needs CS101, directly or indirectly, with its level.
5

Write a function

Hard
Write a SQL function inter.fn_dept_student_count(p_dept_code TEXT) that returns the number of students in a department. Test it with 'CS', 'DA' and a code that doesn't exist, then drop it.
6

A view of each student's load

Medium
Inside a transaction, create a view inter.v_student_load(full_name, courses) giving the number of courses each student takes — including students with none. Use it to list the students with no course. Then try to UPDATE the view: what happens, and why?
7

A trigger that tidies course codes

Hard
Write a BEFORE INSERT OR UPDATE trigger on inter.courses that stores course_code in upper case. Test it inside a transaction by inserting the course 'cs999'.

Exam-style questions

Short answer (2 marks)
  1. List four features of SQL.
  2. Differentiate DELETE, TRUNCATE and DROP.
  3. What is a correlated sub-query?
  4. What is a bind variable? Give one advantage.
  5. What is a cursor?
  6. Differentiate WHERE and HAVING.
  7. What is a view? Differentiate a view and a materialized view.
  8. What is a trigger? Differentiate BEFORE and AFTER triggers.
Long answer (5–10 marks)
  1. Explain the types of SQL commands with examples.
  2. Explain the types of joins with examples.
  3. Explain how an SQL statement is parsed and executed.
  4. Explain hierarchical queries with an example.
  5. Compare functions and stored procedures, with an example of each.
  6. Explain views: creating, updating through a view, WITH CHECK OPTION and materialized views.
  7. Explain triggers with examples: timing, row-level and statement-level, NEW and OLD.
  8. Explain SQL operators, including how NULL is handled.