
--- PDF page 167 ---
U N I T 3 · DATA B A S E S & D E P LOY M E N T




       03
       SQL, NoSQL, Cloud & Deployment
       Where does your app's data live after the server restarts, and how does the app get from
       your laptop onto a server the world can reach? This chapter starts at "what is a table" and
       goes through SQL scripts, joins, normalization and transactions. Then it covers MongoDB
       and when to pick it, S3 file storage, the cloud service models, AWS and DigitalOcean
       droplets, and finally deploying the whole Django + React stack on a droplet. Every Unit 3
       question from the last three papers is answered the way you should write it, and every SQL
       script was run and checked.

          74 marks asked in 3 papers       10 PYQs solved (8 blocks)       5 gaps filled: G4 G5 G6 G9 G18


          All SQL tested




1. Databases & the relational model (3.1–3.2)                    5. PostgreSQL & transactions (3.8–3.9)
2. SQL command groups & scripts (3.3–3.4)                        6. MongoDB, scaling, SQL vs NoSQL (3.10–3.12)
3. Queries, aggregates & joins (3.5–3.6)                         7. Django ORM with SQL vs NoSQL (3.13)
4. Normalization & denormalization (3.7)                         8. S3, cloud models, AWS, DigitalOcean (3.14–3.17)
                                                                 9. Deployment, architecture, revision (3.18–3.22)



▸ Your Unit 3 exam map

                                                                                                 Answered
 PYQ            Paper           Marks   What it asks                                                             In your files?
                                                                                                 in

 A-Q5A          Final 2025-26   10      SQL vs NoSQL in detail (schema, scaling, query style,    3.12             partly   BASE
                                        ACID vs BASE, relationships)                                             missing (G5)

 A-Q5B          Final 2025-26   6       Django ORM with SQL vs NoSQL, ORM vs raw                 3.13             gap G6

 A-Q5C          Final 2025-26   4       Normalization 1NF/2NF/3NF + denormalization              3.7              gap G4


 A-Q1c          Final 2025-26   4       Top-5 students with marks > 75 + their average           3.5              covered

 B-Q4a · C-     2024-25 ·       10 +    What is AWS? Any 5 services                              3.16             gap G9
 Q4b            2023-24         10

 B-Q5a          Final 2024-25   10      SQL script on table Contact                              3.4              partly   ALTER
                                                                                                                 (G18)

--- PDF page 168 ---
Answered
 PYQ            Paper            Marks       What it asks                                                               In your files?
                                                                                                        in

 C-Q5a          Re-Exam          10          SQL script on table Emp                                    3.4               partly   ALTER
                2023-24                                                                                                 (G18)

 B-Q1b · C-     2024-25 ·        5+5         DigitalOcean and droplets                                  3.17              covered   (thin)
 Q1d            2023-24



  ✍️ HOW THIS UNIT IS EXAMINED
  The two older papers asked "do it" questions: a full SQL script (10 M), "What is AWS + 5 services" (10 M)
  and "What are droplets" (5 M). The newest paper (Dec 2025) asked "explain and compare" questions:
  SQL vs NoSQL, the Django ORM with MongoDB, and normalization, all in Q5 (20 M), plus a 4-mark query in
  Q1. Prepare for both. A full Q5 on databases is very likely again.




    3.1 Why an application needs a database
📚 Sources: Unit 3 Notes §1–2          LEC 8 (Databases & Deployment) slides 1–3    One-Shot Revision     Complete Revision deck slide 20


  🧠 START FROM ZERO
  Everything a program keeps in a variable lives in RAM, and RAM is wiped when the server process stops,
  crashes or is redeployed. An app that keeps users, orders and messages only in variables loses all of them
  on every restart. A database is a separate program whose whole job is to store data on disk, keep it cor‐
  rect and safe, and answer questions about it quickly, for many users at the same time.


Exam definition. A database is an organised collection of related data stored electronically. A DBMS (Database
Management System) is the software that stores, retrieves, protects and manages that data, for example
PostgreSQL, MySQL, SQLite (relational) or MongoDB (document/NoSQL).

                          Browser
                                           →
                                                  Django app        →             Database      →         Response
                        sends request               view runs       SQL query     PostgreSQL    rows     HTML / JSON



The database sits behind the application. The browser never talks to it directly. The browser sends a request,
the Django (or FastAPI) app receives it and sends queries to the database, and the rows that come back are
turned into the response.

  Without a database                                                   With a database

  Data is lost on restart                                              Data persists safely on disk (persistence)

  Hard to search or sort                                               Fast queries, filters and sorting (indexes, SQL)

  One user, one file, and a mess when several write at                 Shared by many users at the same time (concurrency)
  once

  Nothing stops bad data                                               Rules enforced on every row: not empty, unique, valid link (in‐
                                                                       tegrity)

--- PDF page 169 ---
Without a database                                            With a database

  A crash halfway through a change leaves a mess                All-or-nothing changes (transactions, 3.9)



  🔑 MEMORY HOOK: WHY A DBMS? "P-I-C-Q-S"
  Persistence · Integrity (rules) · Concurrency (many users) · Querying (fast search) · Security and recovery
  (permissions, backups). Any 2-mark "why do we need a database" answer is these five words with one line
  each.


The course uses one running example: a Student Notes App (LEC 8) built on a simple students +
 departments schema (Unit 3 Notes). We use the same tables below so everything links up.




    3.2 The relational model: tables, keys, types
📚 Sources: Unit 3 Notes §3.1, §3.3   LEC 8 slide 4   Complete Revision deck slide 21   One-Shot Revision


A relational database stores data in tables (relations). One table holds one kind of thing. Tables are linked by
shared values. Students and departments are two kinds of thing, so they live in two tables, and one column con‐
nects them.


  STUDENTS                                                           DEPARTMENTS

    id (PK)     name     email               dept_id (FK)               id (PK)                          name

    1           Asha     asha@mail.com       10                         10                               CS

    2           Ravi     ravi@mail.com       20                         20                               EC

    3           Kiran    kiran@mail.com      NULL                       30                               Mech


                                                                       students.dept_id points at departments.id .
                                                                     Kiran has no department; Mech has no students. We will use
                                                                     those two rows to explain joins in 3.6.



  Term                    Meaning                                                               Example above

  Table (relation)        A collection of related data about one kind of thing                   students

  Row (record, tuple)     One item                                                              One student

  Column (attribute,      One property that every row has                                        name , email
  field)

  Schema                  The structure: tables, columns, types and rules                       The two CREATE TABLEs below

  Primary key (PK)        Column(s) whose value uniquely identifies each row. Unique             students.id
                          and never NULL, one per table

  Composite key           A PK made of two or more columns together                              (student_id, course_id)
                                                                                                in 3.7

--- PDF page 170 ---
Term                    Meaning                                                         Example above

  Candidate key           Any column that could be the PK (unique, not null)               email

  Foreign key (FK)        A column that points at the PK of another table                  students.dept_id → de‐
                                                                                          partments.id

  NULL                    "No value at all". Not zero and not an empty string             Kiran's dept_id



  🧠 REFERENTIAL INTEGRITY: WHAT MAKES IT "RELATIONAL"
  The foreign key is enforced. The database refuses to store a student whose dept_id does not exist in
    departments , and it refuses to delete a department that students still point at. A spreadsheet or a plain file
  cannot give you this guarantee.



▸ Constraints: rules declared once, enforced on every row

              schema.sql: DDL from Unit 3 Notes §3.3


  CREATE TABLE departments (
         id      INT PRIMARY KEY,
         name    VARCHAR(50) NOT NULL UNIQUE
  );


  CREATE TABLE students (
         id         INT PRIMARY KEY,
         name       VARCHAR(80)     NOT NULL,
         email      VARCHAR(120) NOT NULL UNIQUE,
         dept_id    INT REFERENCES departments(id)             -- FK; NULL allowed (no NOT NULL)
  );



 Constraint                       What it enforces                        Example

 PRIMARY KEY                      Unique + never NULL, one per table        id INT PRIMARY KEY

 NOT NULL                         Column must always have a value           name VARCHAR(80) NOT NULL

 UNIQUE                           No two rows may share this value          email ... UNIQUE

 REFERENCES / FOREIGN             Value must exist in the other table's     dept_id INT REFERENCES departments(id)
 KEY                              PK

 DEFAULT                          Value used when none is given             status VARCHAR(10) DEFAULT 'active'

 CHECK extra                      Value must satisfy a condition            marks INT CHECK (marks BETWEEN 0 AND
                                                                          100)


Full forms: PostgreSQL id SERIAL PRIMARY KEY · MySQL id INT AUTO_INCREMENT PRIMARY KEY · SQLite
 id INTEGER PRIMARY KEY AUTOINCREMENT .

Auto-numbered keys. A column declared SERIAL (PostgreSQL) or GENERATED ALWAYS AS IDENTITY (SQL
standard, PostgreSQL 10+) fills in its own increasing number, so you never type IDs by hand:
 id SERIAL PRIMARY KEY (LEC 8 slide 9 uses this for the notes table).

--- PDF page 171 ---
▸ Data types: pick the right one (examiners check this)
Both 10-mark SQL questions say "with appropriate data type for the respective field". This table shows what to
choose in the main databases.

 Store…                 PostgreSQL                     MySQL                     SQLite                 Why

 Whole numbers,          INT , BIGINT                   INT , BIGINT              INTEGER               INT holds up to about 2.1 billion
 IDs

 Money, salary           NUMERIC(10,2) =                DECIMAL(10,2)             NUMERIC               Exact. 10 digits, 2 after the point
                         DECIMAL(10,2)

 Short text:             VARCHAR(n)                     VARCHAR(n)                TEXT (VARCHAR         n = maximum length
 names, email                                                                    accepted)

 Fixed-length            CHAR(n)                        CHAR(n)                   TEXT                  e.g. CHAR(2) state code
 codes

 Long text               TEXT                           TEXT                      TEXT                  No practical limit

 Phone number            VARCHAR(15)                    VARCHAR(15)               TEXT                  Keeps the leading 0 and "+91".
                                                                                                        No maths needed

 True / false            BOOLEAN                        BOOLEAN (=                INTEGER 0/1
                                                        TINYINT(1) )

 Date / date-time        DATE , TIMESTAMP               DATE ,                    TEXT (ISO string)       '2025-12-04'
                                                        DATETIME

 JSON                    JSONB                          JSON                      TEXT                  PostgreSQL's "rich types" (Unit 3
                                                                                                        Notes §4.1)



  ⚠️ TWO TYPE MISTAKES THAT COST MARKS
  Salary as FLOAT. Floating point is approximate ( 0.1 + 0.2 gives 0.30000000000000004 ). Money must
  use DECIMAL(p,s) . Phone as INT. A 10-digit mobile number (9876543210) is bigger than INT's maximum
  (2,147,483,647), and an integer drops a leading 0 and cannot hold "+91". Use VARCHAR(15) . Oracle users
  write VARCHAR2 and NUMBER(10,2) , but standard types are fine in the exam.




    3.3 The five SQL command groups
📚 Sources: Unit 3 Notes §3.2       LEC 8 slide 5   Complete Revision deck slide 22    One-Shot Revision


SQL (Structured Query Language) is the standard declarative language for relational databases. You describe
what you want, and the database decides how to get it. Commands fall into five groups. Your notes call this "a
favourite exam question", and the grouping also explains why different commands need different permissions.

  Group      Full name                  Commands                            Purpose                   One example

  DDL        Data Definition            CREATE, ALTER, DROP,                Define or change          ALTER TABLE emp ADD
             Language                   TRUNCATE                            the structure             email TEXT;

  DML        Data Manipulation          INSERT, UPDATE, DELETE              Change the data           UPDATE emp SET salary =
             Language                                                                                 50000 WHERE id = 3;

--- PDF page 172 ---
Group        Full name                  Commands                           Purpose               One example

  DQL          Data Query Language        SELECT                             Read the data          SELECT * FROM emp;

  DCL          Data Control               GRANT, REVOKE                      Control who can do     GRANT SELECT ON emp TO
               Language                                                      what                  reader;

  TCL          Transaction Control        BEGIN, COMMIT,                     Control transac‐       BEGIN; ... COMMIT;
               Language                   ROLLBACK, SAVEPOINT                tions


Some textbooks put SELECT under DML. Many courses, including yours, list it separately as DQL. In the exam, write "DQL (some
books include it in DML)".


▸ DELETE vs TRUNCATE vs DROP: three ways to remove

                        DELETE                      TRUNCATE                                            DROP

 Group                  DML                         DDL                                                 DDL

 Removes                The rows you choose         Every row                                           The whole table: rows +
                        (WHERE)                                                                         structure

 Table still            Yes                         Yes, empty                                          No
 exists?

 WHERE                  Yes                         No                                                  No
 allowed?

 Speed on big           Slower (row by row)         Fast                                                Fast
 tables

 Undo?                  Yes, inside a transaction   In PostgreSQL yes (inside BEGIN). In MySQL/Oracle   Only inside a transaction in
                                                    it auto-commits                                     PostgreSQL


            three removals


  DELETE FROM students WHERE id = 3;                     -- one chosen row
  TRUNCATE TABLE students;                               -- all rows, empty table remains
  DROP TABLE students;                                   -- table gone (structure included)



  🔑 MEMORY HOOK
  Define · Manipulate · Query · Control · Transact. DDL acts on the box, DML acts on the things in the box,
  DQL looks in the box, DCL hands out keys to the box, TCL decides when changes become final.


   ✏️ CLASSIFY THE COMMAND
    1. ALTER TABLE Emp ADD Contact_No VARCHAR(15); →
    2. REVOKE SELECT ON Emp FROM reader; →
    3. SAVEPOINT gift; →
    4. TRUNCATE TABLE logs; →
    5. UPDATE Emp SET Salary = 48000 WHERE Emp_ID = 3; →

--- PDF page 173 ---
6. The command that removes only chosen rows is                             ; the one that removes the table itself is
                        .

   🔓 Answer key: 1) DDL · 2) DCL · 3) TCL · 4) DDL · 5) DML · 6) DELETE; DROP


    3.4 SQL scripts: CREATE, INSERT, ALTER, UPDATE, DELETE
📚 Sources: Unit 3 Notes §3.3     LEC 8 slide 9   One-Shot Revision (SQL you write by hand · Appendix)   Complete Revision deck slide 24



    🚨 PARTLY MISSING · ALTER TABLE · STEP 3 OF TWO 10-MARK QUESTIONS (2024-25 Q5A,
      2023-24 Q5A)

    Your unit notes teach CREATE, INSERT, UPDATE and DELETE (§3.3), but ALTER TABLE is never taught
    there. It appears only as one line, ALTER TABLE employee ADD email TEXT; , in the One-Shot and
    Complete Revision decks. Yet both 10-mark SQL questions ask you to "add one more column".

    Verdict: MUST LEARN. It is one line, it is worth about 2 marks in each script question, and you also need
    to know the dialect variations. Taught fully below.



▸ The five statements, with their rules

           general forms


  -- DDL: create the structure
  CREATE TABLE table_name (
        column1 datatype constraints,
        column2 datatype constraints,
        ...
  );


  -- DML: add rows (always list the columns; strings in SINGLE quotes)
  INSERT INTO table_name (col1, col2, col3) VALUES
        (v1, 'text', v3),
        (v1, 'text', v3);                           -- many rows in one statement


  -- DDL: change the structure
  ALTER TABLE table_name ADD COLUMN new_col datatype;


  -- DML: change existing rows (WHERE picks WHICH rows)
  UPDATE table_name SET col1 = v1, col2 = v2 WHERE key_col = k;


  -- DML: remove rows
  DELETE FROM table_name WHERE key_col = k;

--- PDF page 174 ---
⚠️ THE THREE CLASSIC SLIPS
         UPDATE or DELETE without WHERE changes every row. DELETE FROM Emp; empties the table.
         Always write the WHERE first.
         String quotes. Use single quotes for values: 'Asha' . In PostgreSQL, double quotes mean an identifier
         (a column name), so "Asha" gives "column Asha does not exist".
         "The 3rd record" has no meaning without a key. A table is an unordered set, and the database may
         return rows in any order. Identify the row by its primary key: WHERE ID = 3 .



▸ ALTER TABLE in full

 Job                 PostgreSQL (and standard SQL)                         MySQL

 Add a column           ALTER TABLE Emp ADD COLUMN Contact_No              same (the word COLUMN is optional)
                     VARCHAR(15);

 Drop a column          ALTER TABLE Emp DROP COLUMN Contact_No;            same

 Rename a               ALTER TABLE Emp RENAME COLUMN F_Name TO            same (MySQL 8+)
 column              First_Name;

 Change a type          ALTER TABLE Emp ALTER COLUMN Salary TYPE            ALTER TABLE Emp MODIFY Salary
                     NUMERIC(12,2);                                        DECIMAL(12,2);

 Add a                  ALTER TABLE Emp ADD CONSTRAINT uq_phone            same
 constraint          UNIQUE (Contact_No);

 Rename the             ALTER TABLE Emp RENAME TO Employee;                 RENAME TABLE Emp TO Employee; (or
 table                                                                     the ALTER form)


Oracle writes ALTER TABLE Emp ADD (Contact_No VARCHAR2(15)); and SQL Server writes
 ALTER TABLE Emp ADD Contact_No VARCHAR(15); . Existing rows get NULL in a new column, unless you add
 DEFAULT ... (then they get the default).


   PYQ        Final 2024-25 · Q5(a)                                                                              10 M


  Write SQL code for the following operations-
  1. Create a table Contact with following fields – ID, firstName, LastName, Email, Salary with appropri‐
  ate data type for the respective field.
  2. Insert five records in the Contact table.
  3. Add one more column "Address" in to this table.
  4. Update 3rd record with new values.
  5. Delete any one record from it.

   ✓     MODEL ANSWER: WRITE THIS

  Assumption: PostgreSQL (standard SQL; also runs on MySQL). ID is the primary key, so "the 3rd record"
  means the row with ID = 3 .

  STEP 1 · CREATE THE TABLE (DDL)

               contact.sql: step 1

--- PDF page 175 ---
CREATE TABLE Contact (
           ID               INT                   PRIMARY KEY,                 -- unique id of each contact
           firstName        VARCHAR(50)           NOT NULL,
           LastName         VARCHAR(50)           NOT NULL,
           Email            VARCHAR(100)          NOT NULL UNIQUE,             -- no two contacts share an email
           Salary           DECIMAL(10,2)         CHECK (Salary >= 0)          -- exact money, 2 decimals
     );


  Type choices: INT for the key, VARCHAR(n) for names and email (variable-length text with a limit), DECIMAL(10,2) for salary be‐
  cause money must be exact (never FLOAT).


  STEP 2 · INSERT FIVE RECORDS (DML)

                contact.sql: step 2


     INSERT INTO Contact (ID, firstName, LastName, Email, Salary) VALUES
           (1, 'Asha',        'Patil', 'asha.patil@mail.com', 45000.00),
           (2, 'Ravi',        'Kumar', 'ravi.kumar@mail.com', 52000.00),
           (3, 'Meena', 'Shah',            'meena.shah@mail.com', 38000.00),
           (4, 'Kiran', 'Rao',             'kiran.rao@mail.com',         61000.00),
           (5, 'Neha',        'Joshi', 'neha.joshi@mail.com', 47000.00);


     SELECT * FROM Contact;



    id          firstname                 lastname               email                                         salary

    1           Asha                      Patil                  asha.patil@mail.com                           45000.00

    2           Ravi                      Kumar                  ravi.kumar@mail.com                           52000.00

    3           Meena                     Shah                   meena.shah@mail.com                           38000.00

    4           Kiran                     Rao                    kiran.rao@mail.com                            61000.00

    5           Neha                      Joshi                  neha.joshi@mail.com                           47000.00


  STEP 3 · ADD THE COLUMN ADDRESS (DDL)

                contact.sql: step 3


     ALTER TABLE Contact ADD COLUMN Address VARCHAR(200);


     SELECT * FROM Contact;                   -- existing rows get NULL in the new column



    id      firstname             lastname               email                                 salary              address

    1       Asha                  Patil                  asha.patil@mail.com                   45000.00            NULL

    2       Ravi                  Kumar                  ravi.kumar@mail.com                   52000.00            NULL

    3       Meena                 Shah                   meena.shah@mail.com                   38000.00            NULL

    4       Kiran                 Rao                    kiran.rao@mail.com                    61000.00            NULL

--- PDF page 176 ---
id       firstname              lastname           email                                   salary             address

    5        Neha                   Joshi              neha.joshi@mail.com                     47000.00           NULL


  STEP 4 · UPDATE THE 3RD RECORD WITH NEW VALUES (DML)

              contact.sql: step 4


     UPDATE Contact
     SET       Email     = 'meena.shah@newmail.com',
               Salary    = 42000.00,
               Address = 'Andheri East, Mumbai'
     WHERE     ID = 3;                         -- WHERE on the primary key = exactly one row


     SELECT * FROM Contact WHERE ID = 3;



    id     firstname        lastname           email                                salary          address

    3      Meena            Shah               meena.shah@newmail.com               42000.00        Andheri East, Mumbai


  STEP 5 · DELETE ANY ONE RECORD (DML)

              contact.sql: step 5


     DELETE FROM Contact WHERE ID = 5;


     SELECT * FROM Contact;



    id     firstname        lastname           email                                salary          address

    1      Asha             Patil              asha.patil@mail.com                  45000.00        NULL

    2      Ravi             Kumar              ravi.kumar@mail.com                  52000.00        NULL

    3      Meena            Shah               meena.shah@newmail.com               42000.00        Andheri East, Mumbai

    4      Kiran            Rao                kiran.rao@mail.com                   61000.00        NULL


  Conclusion line: CREATE and ALTER are DDL (structure), while INSERT, UPDATE and DELETE are DML (data). WHERE on the
  primary key makes sure UPDATE and DELETE touch exactly one row.

  🎯 Marking scheme guess: 2 M CREATE with sensible types and PK · 2 M five-row INSERT · 2 M ALTER TABLE ADD · 2 M UPDATE with
  WHERE · 2 M DELETE with WHERE (output tables / comments earn the "presentation" credit)

--- PDF page 177 ---
⚠️ POSTGRESQL VS MYSQL DETAILS FOR THIS SCRIPT
  Case folding: PostgreSQL turns unquoted names to lower case, so firstName is stored as firstname .
  That is why the output headers above are lower case. It still works as long as you never quote the name. If
  you created it as "firstName" , you must quote it every time. Auto IDs: to let the database number the
  rows, write ID SERIAL PRIMARY KEY (PostgreSQL) or ID INT AUTO_INCREMENT PRIMARY KEY (MySQL)
  and leave ID out of the INSERT. NULL display: psql shows NULL as a blank cell. It is written as NULL
  above for clarity. (Tested with sqlite3 :memory: , which prints 45000 instead of 45000.00 because SQLite
  has no true DECIMAL type.)



   PYQ         Re-Exam 2023-24 · Q5(a)                                                                           10 M


  Write SQL code for the following operations-
  1. Create a table Emp with following fields - F_Name, L_Name , Job –Title, Salary with appropriate
  data type for the respective field.
  2. Insert five records in the emp table.
  3. Add one more column "Contact_No" in to this table.
  4. Update 3rd record with new values.
  5. Delete any one record from it.

   ✓    MODEL ANSWER: WRITE THIS

  Assumptions (instruction 7 on the paper: "Assume suitable data if necessary"):

    1. A hyphen is not allowed in an unquoted SQL name. Job-Title is read as "Job minus Title" and
        gives a syntax error. I name the column Job_Title . To keep the exact name, quote it everywhere:
            "Job-Title" (PostgreSQL/standard) or `Job-Title` (MySQL).

    2. The given fields contain no unique key, so "the 3rd record" cannot be pointed at reliably (rows have
        no fixed order). I add a primary key Emp_ID . Without it, you would have to use a unique combination
        such as WHERE F_Name = 'Meena' AND L_Name = 'Shah' .

  STEP 1 · CREATE TABLE EMP (DDL)

                emp.sql: step 1


       CREATE TABLE Emp (
             Emp_ID        INT             PRIMARY KEY,          -- added: identifies each row
             F_Name        VARCHAR(50)     NOT NULL,
             L_Name        VARCHAR(50)     NOT NULL,
             Job_Title     VARCHAR(50),                          -- "Job-Title" in the question
             Salary        DECIMAL(10,2)   CHECK (Salary > 0)
       );



  STEP 2 · INSERT FIVE RECORDS (DML)

                emp.sql: step 2

--- PDF page 178 ---
INSERT INTO Emp (Emp_ID, F_Name, L_Name, Job_Title, Salary) VALUES
           (1, 'Asha',          'Patil', 'Software Engineer', 65000.00),
           (2, 'Ravi',          'Kumar', 'Data Analyst',                55000.00),
           (3, 'Meena', 'Shah',           'Tester',                     40000.00),
           (4, 'Kiran', 'Rao',            'Project Manager',            90000.00),
           (5, 'Neha',          'Joshi', 'HR Executive',                42000.00);


     SELECT * FROM Emp;



    emp_id                  f_name                l_name                 job_title                                salary

    1                       Asha                  Patil                  Software Engineer                        65000.00

    2                       Ravi                  Kumar                  Data Analyst                             55000.00

    3                       Meena                 Shah                   Tester                                   40000.00

    4                       Kiran                 Rao                    Project Manager                          90000.00

    5                       Neha                  Joshi                  HR Executive                             42000.00


  STEP 3 · ADD COLUMN CONTACT_NO (DDL)

              emp.sql: step 3


     ALTER TABLE Emp ADD COLUMN Contact_No VARCHAR(15);                           -- text, not INT: keeps +91 / leading 0


     SELECT * FROM Emp;



    emp_id              f_name           l_name            job_title                         salary               contact_no

    1                   Asha             Patil             Software Engineer                 65000.00             NULL

    2                   Ravi             Kumar             Data Analyst                      55000.00             NULL

    3                   Meena            Shah              Tester                            40000.00             NULL

    4                   Kiran            Rao               Project Manager                   90000.00             NULL

    5                   Neha             Joshi             HR Executive                      42000.00             NULL


  STEP 4 · UPDATE THE 3RD RECORD (DML)

              emp.sql: step 4


     UPDATE Emp
     SET       Job_Title        = 'Senior Tester',
               Salary           = 48000.00,
               Contact_No = '+91-9876543210'
     WHERE     Emp_ID = 3;
     -- without Emp_ID:             ... WHERE F_Name = 'Meena' AND L_Name = 'Shah';


     SELECT * FROM Emp WHERE Emp_ID = 3;

--- PDF page 179 ---
emp_id               f_name           l_name           job_title               salary            contact_no

    3                    Meena            Shah             Senior Tester           48000.00          +91-9876543210


  STEP 5 · DELETE ANY ONE RECORD (DML)

              emp.sql: step 5


       DELETE FROM Emp WHERE Emp_ID = 4;


       SELECT * FROM Emp;



    emp_id              f_name          l_name          job_title                    salary            contact_no

    1                   Asha            Patil           Software Engineer            65000.00          NULL

    2                   Ravi            Kumar           Data Analyst                 55000.00          NULL

    3                   Meena           Shah            Senior Tester                48000.00          +91-9876543210

    5                   Neha            Joshi           HR Executive                 42000.00          NULL



  🎯 Marking scheme guess: 2 M CREATE (types + handling the hyphen + a key) · 2 M INSERT five rows · 2 M ALTER TABLE ADD
  Contact_No · 2 M UPDATE with WHERE · 2 M DELETE with WHERE



            if you must keep the exact name "Job-Title" (tested)


  CREATE TABLE Emp (
          F_Name               VARCHAR(50) NOT NULL,
          L_Name               VARCHAR(50) NOT NULL,
          "Job-Title"          VARCHAR(50),                    -- MySQL: `Job-Title`          SQL Server: [Job-Title]
          Salary               DECIMAL(10,2)
  );
  UPDATE Emp SET "Job-Title" = 'Senior Tester', Salary = 48000
  WHERE     F_Name = 'Meena' AND L_Name = 'Shah';                     -- no key, so match on a unique combination


  -- Unquoted Job-Title fails:                  ERROR: syntax error at or near "-"


Some students use SQLite's hidden rowid or MySQL's LIMIT 1 OFFSET 2 to reach "the 3rd row". Avoid both in the exam:
without ORDER BY the order is not guaranteed, and rowid only exists in SQLite. Adding a primary key is the answer examiners
expect.

--- PDF page 180 ---
✏️ FILL IN THE BLANKS: THE SQL SCRIPT
                   blanks in code


       ______ TABLE Student (
                 Roll_No    INT ______ ______,
                 Name       ______(60) NOT NULL,
                 Fees       ______(10,2)
       );
       ______ ______ Student (Roll_No, Name, Fees) ______ (1, 'Asha', 55000.00);
       ______ TABLE Student ______ COLUMN City VARCHAR(40);
       ______ Student ______ City = 'Pune' ______ Roll_No = 1;
       ______ ______ Student WHERE Roll_No = 1;



   🔓 Answer key: CREATE · PRIMARY KEY · VARCHAR · DECIMAL (or NUMERIC) · INSERT INTO · VALUES · ALTER · ADD · UPDATE ·
   SET · WHERE · DELETE FROM




    3.5 Querying: filter, sort, limit, aggregate, group
📚 Sources: Unit 3 Notes §3.4        LEC 8 slide 6   Complete Revision deck slides 23–24      One-Shot Revision


A SELECT reads data. You build it from clauses, and each clause has one job. We use this students table,
with marks this time:

                 students.sql: sample data used below


  CREATE TABLE students (
            id          INT PRIMARY KEY,
            name        VARCHAR(80) NOT NULL,
            marks       INT CHECK (marks BETWEEN 0 AND 100)
  );
  INSERT INTO students (id, name, marks) VALUES
    (1,'Asha',92), (2,'Ravi',68), (3,'Meena',81), (4,'Kiran',77), (5,'Neha',95),
    (6,'Arjun',74), (7,'Sara',88), (8,'Dev',79),                   (9,'Isha',60), (10,'Om',85);




▸ WHERE: filter rows

 Operator                        Example                                              Meaning

 = , <> (or !=)                  WHERE name = 'Asha'                                  equal / not equal

 > < >= <=                       WHERE marks > 75                                     comparison (strictly greater: 75 itself is excluded)

 BETWEEN a AND b                 WHERE marks BETWEEN 70 AND 80                        inclusive range

 IN (...)                        WHERE id IN (1, 3, 5)                                matches any value in the list

 LIKE                            WHERE name LIKE 'A%'                                     % = any characters, _ = exactly one character

--- PDF page 181 ---
Operator                 Example                                                Meaning

 IS NULL / IS NOT NULL        WHERE dept_id IS NULL                              never write = NULL (it is never true)

 AND, OR, NOT                 WHERE marks > 75 AND name LIKE 'S%'                combine conditions



▸ ORDER BY and LIMIT: sort, then keep the first N
 ORDER BY marks DESC sorts highest first ( ASC , the default, sorts lowest first). Add a second column to break
ties: ORDER BY marks DESC, name ASC . LIMIT 5 keeps the first 5 rows of the sorted result. OFFSET 5 skips
5 rows first, which is how page 2 is built.

 Database                                "Top 5" syntax

 PostgreSQL, MySQL, SQLite                ... ORDER BY marks DESC LIMIT 5;

 SQL standard, Oracle 12c+,               ... ORDER BY marks DESC FETCH FIRST 5 ROWS ONLY;
 PostgreSQL

 SQL Server                               SELECT TOP 5 name, marks FROM students ... ORDER BY marks
                                         DESC;



▸ Aggregate functions: many rows → one value

 Function                                     Returns                                         On our data (all 10 rows)

  COUNT(*)                                    number of rows                                  10

  COUNT(col)                                  number of non-NULL values in col                10

  SUM(marks)                                  total                                           799

  AVG(marks)                                  mean (NULLs ignored)                            79.9

  MIN(marks) / MAX(marks)                     smallest / largest                              60 / 95


 AS gives a result column a readable name (an alias): SELECT AVG(marks) AS avg_marks .
 ROUND(AVG(marks), 2) keeps two decimals.


▸ GROUP BY and HAVING: one result row per group
 GROUP BY dept_id makes one group per department, and the aggregate then runs once per group. HAVING
filters groups, the way WHERE filters rows.

            Unit 3 Notes §3.4 example


  SELECT dept_id, COUNT(*) AS total
  FROM students
  WHERE dept_id IS NOT NULL             -- 1) drop rows with no department
  GROUP BY dept_id                      -- 2) one group per department
  HAVING COUNT(*) > 1                   -- 3) keep groups with more than one student
  ORDER BY total DESC                   -- 4) alias "total" is usable here
  LIMIT 5;

--- PDF page 182 ---
▸ Written order vs execution order

 You write              DB runs            Clause              What it does

 1                      5                  SELECT              Picks columns, computes expressions, creates aliases

 2                      1                  FROM + JOIN         Chooses and combines the tables

 3                      2                  WHERE               Filters rows, before any grouping

 4                      3                  GROUP BY            Forms groups of rows

 5                      4                  HAVING              Filters groups, after grouping

 6                      6                  ORDER BY            Sorts the result

 7                      7                  LIMIT               Keeps only the first N rows



  🔑 MEMORY HOOK FOR THE RUN ORDER
  From → Where → Group → Having → Select → Order → Limit: "Fresh Water Gives Healthy Students Only
  Laughs". Two facts follow from it. (1) A SELECT alias does not exist yet when WHERE runs, so
     WHERE total > 1 fails, but ORDER BY total works. (2) WHERE cannot contain an aggregate
  ( WHERE COUNT(*) > 1 is an error), so aggregate conditions go in HAVING.



     PYQ         Final 2025-26 · Q1(c)   ★ LATEST                                                                                4M


  Write an SQL query that lists the top 5 students with marks > 75, ordered by marks descending. Also
  write a query to calculate the average marks of all students who scored above 75.

     ✓    MODEL ANSWER: WRITE THIS

  Assume the table students(id, name, marks) .

                  Query 1: top 5 students with marks > 75


         SELECT id, name, marks
         FROM     students
         WHERE    marks > 75                       -- filter rows first
         ORDER    BY marks DESC                    -- highest marks first
         LIMIT    5;                               -- keep only the top 5
         -- SQL Server: SELECT TOP 5 ...                 Oracle/standard: FETCH FIRST 5 ROWS ONLY



                  Query 2: average marks of all students above 75


         SELECT ROUND(AVG(marks), 2) AS avg_above_75
         FROM     students
         WHERE    marks > 75;                      -- WHERE (not HAVING): we filter rows, there is no grouping

--- PDF page 183 ---
OUTPUT 1                                                              OUTPUT 2

       id             name                  marks                             avg_above_75

       5              Neha                  95                                85.29

       1              Asha                  92
                                                                           7 students score above 75 (92, 81, 77, 95, 88, 79, 85). 597
       7              Sara                  88                             / 7 = 85.29. Kiran (77) and Dev (79) count in the average
                                                                           even though they are not in the top 5.
       10             Om                    85

       3              Meena                 81



  How it runs: FROM students → WHERE keeps marks > 75 → SELECT → ORDER BY marks DESC →
  LIMIT 5. Query 2 uses the aggregate AVG() over the filtered rows.

  🎯 Marking scheme guess: 1 M correct WHERE · 1 M ORDER BY … DESC · 0.5 M LIMIT 5 · 1.5 M AVG query with WHERE marks > 75

  ⚠️ TRAPS IN THIS EXACT QUESTION
       Do not put LIMIT 5 on the average query. The question says "all students who scored above 75" (7
       students, 85.29), not "the top 5" (that would be 88.20). If you ever need the average of the top 5, use a
       subquery (result 88.20):

                   average of the top 5 only (not what was asked)


            SELECT AVG(marks) FROM (
                SELECT marks FROM students WHERE marks > 75 ORDER BY marks DESC LIMIT 5
            ) AS t;



           > 75 excludes exactly 75. If the paper said "75 and above", use >= 75 .

       Don't write HAVING marks > 75 . HAVING belongs with GROUP BY and aggregates.



   ✏️ PREDICT THE OUTPUT (SAME 10-STUD ENT TABL E)
    1. SELECT COUNT(*) FROM students WHERE marks BETWEEN 74 AND 81; →
    2. SELECT name FROM students ORDER BY marks ASC LIMIT 2; →
    3. SELECT MAX(marks) - MIN(marks) AS spread FROM students; →
    4. SELECT name FROM students WHERE name LIKE '_a%'; →
    5. Why does SELECT name, marks*1.1 AS scaled FROM students WHERE scaled > 90; fail?



   🔓 Answer key: 1) 4 (Meena 81, Kiran 77, Arjun 74, Dev 79) · 2) Isha, Ravi · 3) 35 · 4) Ravi, Sara (second letter is "a") · 5) WHERE runs
   before SELECT, so the alias "scaled" does not exist yet. Repeat the expression: WHERE marks*1.1 > 90

--- PDF page 184 ---
3.6 Joins: combining tables
📚 Sources: Unit 3 Notes §3.5           LEC 8 slides 7–8    Complete Revision deck slide 25   One-Shot Revision


A join combines rows from two tables by matching them with a condition written after ON , usually foreign key =
primary key. The join type decides what happens to rows that find no match.

            join syntax: swap INNER for LEFT, RIGHT or FULL OUTER


  SELECT s.name AS student, d.name AS department
  FROM       students s                                                -- s and d are table aliases
  INNER      JOIN departments d ON d.id = s.dept_id;



                                                                        Result with our tables (Kiran has no dept, Mech
  Join                      Rows returned                                                                                           Rows
                                                                        has no students)

  INNER JOIN                Only rows that match in both tables         Asha-CS, Ravi-EC                                            2

  LEFT JOIN                 Every left row + matches (NULL              Asha-CS, Ravi-EC, Kiran-NULL                                3
                            where none)

  RIGHT JOIN                Every right row + matches from the          Asha-CS, Ravi-EC, NULL-Mech                                 3
                            left

  FULL OUTER                Every row from both, matched where          Asha-CS, Ravi-EC, Kiran-NULL, NULL-Mech                     4
  JOIN                      possible

  CROSS JOIN                Every row × every row, no ON                each student with each department                           3×3=
                                                                                                                                    9

  SELF JOIN                 A table joined to itself with two           pairs of students in the same department                    de‐
                            aliases                                                                                                 pends


          left = students                                                                                            right = departments




                      INNER                               LEFT                          RIGHT                     FULL OUTER

                  Shaded = rows kept. The overlap is the matched pairs; the outer parts are unmatched rows padded with NULL.


            self join: students in the same department (Unit 3 Notes §3.5)


  SELECT a.name, b.name
  FROM       students a
  JOIN       students b ON a.dept_id = b.dept_id AND a.id < b.id;
  -- a.id < b.id removes "Asha-Asha" and stops each pair appearing twice (Asha-Meena / Meena-Asha)

--- PDF page 185 ---
join + group: students per department, including empty ones (tested)


  SELECT d.name, COUNT(s.id) AS total                        -- COUNT(s.id) skips the NULL, so Mech shows 0
  FROM       departments d
  LEFT       JOIN students s ON s.dept_id = d.id
  GROUP      BY d.name
  ORDER      BY total DESC;                                     -- CS 1 · EC 1 · Mech 0 (Mech appears only because of
  LEFT JOIN)



  ✍️ HOW TO ANSWER "HOW MANY ROWS WILL THIS JOIN RETURN?"
  Don't guess. Write the INNER matches first, then add the unmatched rows that the join type keeps: LEFT
  adds unmatched left rows, RIGHT adds unmatched right rows, FULL adds both. Your notes recommend
  exactly this method.


   ✏️ JOIN DRILL
   Table A(id) = {1, 2, 3, 4}; table B(a_id) = {2, 4, 4, 7}. Join on A.id = B.a_id .

    1. INNER JOIN returns                        rows.
    2. LEFT JOIN (A left) returns                       rows.
    3. RIGHT JOIN returns                        rows.
    4. FULL OUTER JOIN returns                            rows.
    5. CROSS JOIN returns                         rows.

   🔓 Answer key: 1) 3 (2-2, 4-4, 4-4) · 2) 5 (3 matches + unmatched 1 and 3) · 3) 4 (3 matches + unmatched 7) · 4) 6 (3 + 1, 3 + 7) · 5) 16
   (4 × 4)




    3.7 Normalization and denormalization
📚 Sources: Not in your files — added from standard references
     🚨 NOT IN YOUR STUDY MATERIAL · 4 MARKS · FINAL 2025-26 Q5(C)
     None of your 22 study files mention normalization, normal forms or denormalization. The notes only
     show the result: data split into students and departments and linked by a foreign key. They never ex‐
     plain why it is split that way.

     Verdict: MUST LEARN. It is a standard DBMS question, the newest paper asked it, and it takes 20 min‐
     utes to learn. It also gives you the vocabulary for 3.12: NoSQL "embedding" is a form of denormalization.

--- PDF page 186 ---
🧠 START FROM ZERO
  Normalization is the process of organising a relational database into tables so that each fact is stored in
  exactly one place. This removes redundancy (repeated data) and the anomalies that repeated data caus‐
  es. You apply it step by step through normal forms (1NF → 2NF → 3NF). Each form adds one rule on top
  of the previous one.


  💡 THINK OF IT LIKE
  A class contact list where every assignment entry rewrites the student's phone number. When Asha
  changes her number, you must find and fix every entry, and if you miss one, the list contradicts itself.
  Normalization keeps one "Students" page with each phone number written once, and every other page just
  says "student 101".



▸ One key idea first: functional dependency
A → B ("A determines B") means: if you know A, there is exactly one B. student_id → student_name holds
(one id, one name). dept → hod holds (one department, one head). Every normal form is a rule about which
column may depend on which.


▸ Worked example: un-normalized → 1NF → 2NF → 3NF

UN-NORMALIZED (UNF): THE WAY A PAPER FORM LOOKS

 student_id              student_name           dept         hod             courses (code, title, marks)

 101                     Asha                   CS           Dr. Rao         C1 DBMS 82, C2 Python 91

 102                     Ravi                   EC           Dr. Iyer        C1 DBMS 74

 103                     Meena                  CS           Dr. Rao         C2 Python 68, C3 Cloud 88


Problem: the courses cell holds a list (a repeating group). You cannot query "all students in C2" or average the
marks without splitting text.

1NF: ATOMIC VALUES, NO REPEATING GROUPS

Rule: every cell holds one single (atomic) value, every row is unique (it has a primary key), and there are no re‐
peating groups. Fix: one row per student-course pair. The PK becomes the composite
 (student_id, course_id) .

 student_id             student_name       dept        hod              course_id         course_title             marks

 101                    Asha               CS          Dr. Rao          C1                DBMS                     82

 101                    Asha               CS          Dr. Rao          C2                Python                   91

 102                    Ravi               EC          Dr. Iyer         C1                DBMS                     74

 103                    Meena              CS          Dr. Rao          C2                Python                   68

 103                    Meena              CS          Dr. Rao          C3                Cloud                    88

--- PDF page 187 ---
It is now in 1NF, but look at the repetition. "Dr. Rao" appears 3 times, "DBMS" twice, "Asha" twice. That causes
the three anomalies:

 Anomaly                What goes wrong in the 1NF table

 Update anomaly         CS gets a new HOD, so 3 rows must change. Miss one and the data contradicts itself.

 Insert anomaly         A new course "C4 AI" cannot be stored until some student enrolls, because the PK needs a student_id.

 Delete anomaly         Delete Ravi's only enrollment and you also lose Ravi himself and the fact that EC's HOD is Dr. Iyer.


2NF: NO PARTIAL DEPENDENCY

Rule: 1NF + every non-key column depends on the whole primary key, not just part of a composite key. Here
 student_name, dept, hod depend only on student_id , and course_title depends only on course_id .
Only marks needs both. Fix: move each partial group into its own table.


  STUDENT                                         COURSE                                          ENROLLMENT
  student_id PK, student_name, dept,              course_id PK, course_title                      (student_id, course_id) PK, both
  hod                                                                                             FKs, marks



3NF: NO TRANSITIVE DEPENDENCY

Rule: 2NF + no non-key column depends on another non-key column. In STUDENT,
 student_id → dept → hod : hod depends on dept, not directly on the student. This is a transitive dependen‐
cy. Fix: move department facts into a DEPARTMENT table.


  DEPARTMENT                                                              COURSE

    dept_id             dept_name                hod                         course_id                           title

    10                  CS                       Dr. Rao                     C1                                  DBMS

    20                  EC                       Dr. Iyer                    C2                                  Python

                                                                             C3                                  Cloud
  STUDENT
                                                                          ENROLLMENT
    student_id           student_name              dept_id

    101                  Asha                      10                        student_id             course_id              marks

    102                  Ravi                      20                        101                    C1                     82

    103                  Meena                     10                        101                    C2                     91

                                                                             102                    C1                     74

                                                                             103                    C2                     68

                                                                             103                    C3                     88



Every fact now lives once. A new HOD is a one-row UPDATE. Course C4 can be inserted on its own. Deleting an
enrollment never deletes a student. This is exactly the shape of students + departments in your notes.

           normalized_3nf.sql (tested in sqlite3)

--- PDF page 188 ---
CREATE TABLE department (
         dept_id          INT PRIMARY KEY,
         dept_name        VARCHAR(30) NOT NULL UNIQUE,
         hod              VARCHAR(50));
  CREATE TABLE student (
         student_id           INT PRIMARY KEY,
         student_name VARCHAR(80) NOT NULL,
         dept_id              INT REFERENCES department(dept_id));
  CREATE TABLE course (
         course_id        VARCHAR(10) PRIMARY KEY,
         title            VARCHAR(80) NOT NULL);
  CREATE TABLE enrollment (
         student_id INT REFERENCES student(student_id),
         course_id        VARCHAR(10) REFERENCES course(course_id),
         marks            INT,
         PRIMARY KEY (student_id, course_id));                        -- composite key


  -- JOINs rebuild the original wide view whenever you need it:
  SELECT s.student_name, d.dept_name, d.hod, c.title, e.marks
  FROM      enrollment e
  JOIN      student s            ON s.student_id = e.student_id
  JOIN      course c             ON c.course_id        = e.course_id
  JOIN      department d ON d.dept_id                  = s.dept_id;



  Form                  Rule (one line for the exam)                                                  Removes

  1NF                   Atomic values, no repeating groups or lists, each row identified by a key     Multi-valued cells

  2NF                   1NF + no partial dependency: non-key columns depend on the whole              Facts about part of the key
                        composite key

  3NF                   2NF + no transitive dependency: non-key columns depend only on the            Facts about other non-key
                        key                                                                           columns

  BCNF                  Stricter 3NF: every determinant (left side of A → B) is a candidate key       Rare leftover anomalies
   bonus




  🔑 MEMORY HOOK (CODD'S OATH)
  Every non-key column must depend on "the key (1NF), the whole key (2NF), and nothing but the key
  (3NF)". A table with a single-column PK is automatically in 2NF once it is in 1NF, because a partial depen‐
  dency needs a composite key.

--- PDF page 189 ---
▸ Denormalization: breaking the rules on purpose
Denormalization means deliberately adding redundancy, such as copied columns, pre-computed totals or pre-
joined tables, so that reads become faster because fewer joins or calculations are needed. The price is extra
storage and the job of keeping the copies in sync.

 Example                Normalized way                  Denormalized way                            Why it helps

 Social media            COUNT(*) over the likes ta‐    A like_count column on posts ,              The feed is read millions of
 like count             ble every time the feed loads   +1 on each like                             times; counting each time is
                                                                                                    slow

 E-commerce             Join to products for name and   Copy product_name and                       Faster invoices, and it keeps the
 order line             price                            unit_price into order_items                price at time of purchase

 Reports /              5-table join per chart          A pre-joined reporting table or material‐   Analytics queries become sim‐
 dashboards                                             ized view, refreshed nightly                ple scans

 MongoDB post           Reference the author by id      Embed {author: {name,                       One read shows the post, with
                                                        avatar}} inside each post                   no join


When it is beneficial: read-heavy workloads, where data is read far more often than it is written; expensive joins
on very large tables; reporting and analytics; and distributed NoSQL stores that have no joins. When to avoid it:
data that changes often, or that must be strictly consistent (balances, stock levels), unless you also add triggers
or application code to keep the copies in sync.


   PYQ        Final 2025-26 · Q5(C)   ★ LATEST                                                                                  4M


  Explain database normalization. What are the first three normal forms (1NF, 2NF, 3NF)? Why is nor‐
  malization important in relational databases? Give one example of denormalization and when it might
  be beneficial.

   ✓   MODEL ANSWER: WRITE THIS

  Normalization is the process of organising data in a relational database into well-structured tables, using
  primary and foreign keys, so that each fact is stored only once. This removes redundancy and the insert,
  update and delete anomalies it causes. It is done in stages called normal forms.

       1NF: every cell holds one atomic value, there are no repeating groups or lists, and each row has a key.
       e.g. "C1, C2" in one cell becomes two rows.
       2NF: 1NF + no partial dependency. With a composite key (student_id, course_id), course_title de‐
       pends only on course_id, so it moves to a separate COURSE table.
       3NF: 2NF + no transitive dependency. In STUDENT(student_id, dept, hod), hod depends on dept rather
       than on the key, so DEPARTMENT(dept, hod) becomes its own table.

  Why it is important: (1) no redundant copies, so less storage; (2) no update/insert/delete anomalies, so the
  data stays consistent; (3) integrity is enforced through PK/FK; (4) the schema is clean and easy to extend.
  That is why banking and ERP systems use normalized schemas.

  Denormalization example: a social media app stores like_count directly in the posts table instead of
  running COUNT(*) on the likes table on every feed load. It is beneficial when the workload is read-heavy
  and joins or aggregates are expensive (feeds, dashboards, reports), and the small risk of a stale copy is

--- PDF page 190 ---
acceptable.

  🎯 Marking scheme guess: 1 M definition + purpose · 1.5 M 1NF/2NF/3NF with rule + example · 0.5 M importance · 1 M denormalization
  example + when




   ✏️ WHICH NORMAL FORM IS BROKEN?
    1. Orders(order_id, customer, items = 'pen, book, ink') breaks                                               .
    2. Enrollment(student_id, course_id, course_title, marks) , PK (student_id, course_id), breaks
                        because                   depends only on course_id.
    3. Employee(emp_id PK, name, dept_id, dept_location) breaks                                              (transitive: emp_id →
       dept_id → dept_location).
    4. A 1NF table whose PK is a single column is automatically in                                 .
    5. Storing order_total in orders although it can be computed from order_items is                                                  .

   🔓 Answer key: 1) 1NF · 2) 2NF; course_title · 3) 3NF · 4) 2NF · 5) denormalization


    3.8 PostgreSQL in practice
📚 Sources: Unit 3 Notes §4       LEC 8 slide 9    Unit 2 Notes §6      LEC 5 (Django code-along)       One-Shot Revision


PostgreSQL ("Postgres") is a free, open-source relational database (RDBMS) with a very large community. It is
the SQL database used throughout this course because it combines strict correctness with enough features to
power large applications.

 Feature                         Why it matters

 ACID transactions               Safe, all-or-nothing changes (3.9)

 Open source                     Free to use, with a huge community and documentation

 Rich data types                 JSON/JSONB, arrays, dates and UUIDs are first-class types

 Extensible                      Scales from a laptop to a large application, and supports extensions (e.g. PostGIS for maps)

 Standards + Django              Very close to the SQL standard. Django's ORM supports it fully with django.db.backends.post‐
 support                         gresql


SQLite vs PostgreSQL (from Unit 2): SQLite is one file inside the project, needs no setup, and is good for learn‐
ing, but it locks the whole file when someone writes. PostgreSQL is a separate server process (port 5432) built
for many users writing at once, which makes it the production choice. Django talks to both through the ORM, so
switching is a configuration change, not a rewrite.


▸ Running PostgreSQL in a container

           compose.yaml: the db service (Unit 3 Notes §4.2)


  services:
     db:
        image: postgres:16

--- PDF page 191 ---
environment:
           POSTGRES_USER: appuser                   # first user, created on first start
           POSTGRES_PASSWORD: change-me             # its password
           POSTGRES_DB: appdb                       # first database
        ports:
           - "127.0.0.1:5432:5432"                  # only this machine can connect
        volumes:
           - pgdata:/var/lib/postgresql/data              # data survives container deletion
        healthcheck:
           test: ["CMD-SHELL", "pg_isready -U appuser -d appdb"]
           interval: 5s
           timeout: 3s
           retries: 12
  volumes:
     pgdata:



    The three POSTGRES_ variables create the first user, password and database the first time the container
    starts on an empty volume.
     pgdata is a named volume. You can delete and recreate the container and the data survives.

    Publishing on 127.0.0.1 keeps the database off the network. Publishing on all addresses would expose it.
    The healthcheck lets other services wait until Postgres is actually ready, not merely started. Volumes and
    healthchecks are covered in depth in the Unit 5 chapter.

           terminal


  docker compose up -d db                                                # start the service in the background
  docker compose exec db psql -U appuser -d appdb                        # open the psql client inside it



 psql command                           Effect

  \dt                                   List the tables

  \d table_name                         Show a table's columns, primary key and foreign keys

  \i file.sql                           Run the SQL stored in a file

  \l · \c dbname                        List databases · connect to another one

  \q                                    Quit psql


Backslash commands belong to psql itself, not to SQL. They need no semicolon. SQL statements always end with ; .



▸ Using PostgreSQL from Python (psycopg)

           db.py (Unit 3 Notes §4.3)


  import os
  import psycopg
  from psycopg.rows import dict_row

--- PDF page 192 ---
DATABASE_URL = os.environ["DATABASE_URL"]           # postgresql://user:password@host:5432/dbname


  def connect():
        return psycopg.connect(DATABASE_URL, row_factory=dict_row)          # rows come back as dicts


  def get_student(student_id):
        with connect() as conn:                                           # block = one transaction
              return conn.execute(
                   "SELECT id, name FROM students WHERE id = %s", (student_id,)        # %s placeholder
              ).fetchone()


  def students_with_department():
        sql = """
              SELECT s.name AS student, d.name AS department
              FROM students s
              LEFT JOIN departments d ON d.id = s.dept_id
              ORDER BY s.name
        """
        with connect() as conn:
              return conn.execute(sql).fetchall()



Two ideas matter beyond the syntax. (1) A with connect() as conn block is a transaction: it commits when
the block finishes normally and rolls back if an error escapes it. (2) The %s placeholders send values separate‐
ly from the SQL text, so a value can never be run as SQL.

  ⚠️ SQL INJECTION
              WRONG: never build SQL with f-strings


     conn.execute(f"SELECT * FROM students WHERE name = '{name}'")
     # name = "' OR '1'='1"        →   WHERE name = '' OR '1'='1'     → returns EVERY student



  Always pass values as parameters ( %s + a tuple). Django's ORM does this for you automatically, and raw
  Django SQL uses the same placeholder: cursor.execute("... WHERE id = %s", [user_id]) (Unit 2
  Notes §6.4).



▸ Pointing Django at PostgreSQL

           settings.py


  DATABASES = {
        "default": {
              "ENGINE": "django.db.backends.postgresql",
              "NAME": "appdb",
              "USER": "appuser",
              "PASSWORD": os.environ["POSTGRES_PASSWORD"],         # never hard-code secrets

--- PDF page 193 ---
"HOST": "db",                 # compose service name. Unit 2 used "localhost" (Postgres on the
  same machine)
               "PORT": "5432",
         }
  }


Driver: Unit 2 installs psycopg2-binary , Unit 3 uses psycopg (version 3). Django 4.2+ works with either. After switching, run
 python manage.py migrate again to create every table in the new database. Why HOST changes: inside a container,
 localhost means that container itself, so Django must reach Postgres by its compose service name db (more in 3.18).




      3.9 Transactions and ACID
📚 Sources: Unit 3 Notes §5          LEC 8 slides 10–13   Complete Revision deck slide 26     One-Shot Revision


A transaction is a group of SQL statements treated as one unit of work: either all of them take effect or none
do. The standard example is a bank transfer: debit A by 500, then credit B by 500. If the server crashes after the
debit but before the credit, the money has vanished. A transaction makes that impossible.

                                       Debit A            Credit B              COMMIT                  any step fails
                   BEGIN     →           − 500
                                                    →       + 500
                                                                         →        saved
                                                                                               |    ROLLBACK: both undone



  ACID
                    Meaning                                              How to picture it
  property

  Atomicity         All the steps happen, or none do                     ROLLBACK undoes both the debit and the credit

  Consisten‐        The database's rules hold before and after           A foreign key or CHECK violation is refused, so the data nev‐
  cy                                                                     er becomes invalid

  Isolation         Transactions running at the same time do             Another session cannot see your uncommitted changes
                    not interfere

  Durability        Once committed, the change survives a                The committed row is still there after a restart (it was written
                    crash                                                to disk/WAL)


Note from your notes: consistency is about rules, not business logic. The database enforces only what it was told (types, NOT NULL,
UNIQUE, FK, CHECK). It cannot know that a transfer must debit and credit the same amount unless the app puts both statements in
one transaction.

--- PDF page 194 ---
▸ The life of a transaction


                                     last statement runs                                     COMMIT
                                                                  Partially
                   Active                                                                                        Committed
                                                                 committed


                                                                         error or crash
                                  error
                                                                                            ROLLBACK
                                                                   Failed                                           Aborted



               Every transaction ends in exactly one final state: Committed (changes permanent) or Aborted (every change undone)


 State                        Meaning                                                                    Moves to

 Active                       Running its statements                                                     Partially committed, or Failed

 Partially committed          Last statement has run, but the result is not yet permanent                Committed, or Failed

 Committed                    COMMIT succeeded, so the changes are permanent                             final

 Failed                       An error or crash means it cannot continue                                 Aborted

 Aborted                      ROLLBACK has run and every change is undone                                final



▸ Types of transactions

 Type             How it works                                                                                     Example

 Flat (simple)    One BEGIN-to-COMMIT block, all or nothing                                                        A bank transfer

 Nested           Sub-transactions inside a parent, and a child can roll back alone                                An order with an optional
                                                                                                                   gift-wrap step

 Distributed      Spans several databases or servers, and all commit together using two-phase commit               Booking a flight and a ho‐
                  (every participant first promises "I can commit", then everyone commits)                         tel together

 Auto-            Each single statement is its own transaction                                                     A plain UPDATE typed in
 commit                                                                                                            psql

 Explicit         You decide where it starts and ends with BEGIN and COMMIT                                        Several statements that
                                                                                                                   must go together


PostgreSQL has no true nested transactions. It gets the same effect with SAVEPOINT .



▸ Controlling transactions in SQL (TCL)

            transfer.sql + savepoint.sql (tested in sqlite3)


  -- all or nothing
  BEGIN;
  UPDATE accounts SET balance = balance - 500 WHERE id = 1;
  UPDATE accounts SET balance = balance + 500 WHERE id = 2;
  COMMIT;                       -- or ROLLBACK; to undo both

--- PDF page 195 ---
-- undo only part of a transaction
  BEGIN;
  INSERT INTO orders VALUES (1, 'Book');
  SAVEPOINT gift;
  INSERT INTO orders VALUES (2, 'Gift wrap');
  ROLLBACK TO gift;          -- only the gift wrap is undone
  COMMIT;                    -- order 1 is saved



 Command                                                        Job

  BEGIN (or START TRANSACTION )                                 Start a transaction

  COMMIT                                                        Save all the changes permanently

  ROLLBACK                                                      Undo all the changes since BEGIN

  SAVEPOINT name                                                Mark a point to roll back to

  ROLLBACK TO name                                              Undo only the work done after that savepoint


    No BEGIN means auto-commit: each statement is saved immediately. So a transfer needs BEGIN.
    An error inside a transaction (e.g. a foreign-key violation) makes PostgreSQL refuse every further com‐
    mand with "current transaction is aborted, commands ignored until end of transaction block". This is the
    Failed → Aborted step. The only way forward is ROLLBACK .
    Sequence numbers are not rolled back. A rolled-back INSERT still uses up its SERIAL number, so gaps in
    an ID column are normal.

Isolation levels (beyond your notes): Read Uncommitted, Read Committed (PostgreSQL's default), Repeatable Read and Serializable.
Each stricter level blocks more anomalies: dirty reads (seeing uncommitted data), non-repeatable reads (the same row changes between
two reads) and phantoms (new rows appear when a query runs again).



▸ Transactions in Django, and DCL

           views.py: Django's ORM version of BEGIN … COMMIT


  from django.db import transaction


  def transfer(a, b, amount):
        with transaction.atomic():                # BEGIN; any exception → ROLLBACK, else COMMIT
             a.balance -= amount
             a.save()
             b.balance += amount
             b.save()



Transactions protect the correctness of changes. DCL decides who may make them:

--- PDF page 196 ---
roles.sql (Unit 3 Notes §5.4)


  CREATE ROLE reader NOLOGIN;
  GRANT     SELECT ON ALL TABLES IN SCHEMA public TO reader;                       -- reader can read but not DELETE
  REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM reader;




   ✏️ PREDICT THE BALANCE (TESTED)
    accounts has A = 500. Then:

                 predict


        BEGIN;
        UPDATE accounts SET balance = balance + 100 WHERE id = 1;
        SAVEPOINT s1;
        UPDATE accounts SET balance = balance + 50               WHERE id = 1;
        ROLLBACK TO s1;
        UPDATE accounts SET balance = balance + 10               WHERE id = 1;
        COMMIT;



    1. Final balance of A =
    2. If the last line were ROLLBACK; instead of COMMIT; , A =
    3. The ACID property that guarantees (2) is                        ; the one that keeps 610 after a power cut is
                        .
    4. Without                  , PostgreSQL runs in                     mode and saves every statement immediately.

   🔓 Answer key: 1) 610 (500 + 100 + 10; the +50 was undone) · 2) 500 · 3) Atomicity; Durability · 4) BEGIN; auto-commit


    3.10 NoSQL and MongoDB
📚 Sources: Unit 3 Notes §6.1–6.5      LEC 8 slides 14–15    Complete Revision deck slide 27    One-Shot Revision (incl. Appendix)


In a SQL table every row must have the same shape. That is a strength when data is regular and a limitation
when it is not. NoSQL ("Not only SQL") databases drop the fixed table. MongoDB, the NoSQL database in this
course, stores each record as a document: a JSON-like object (stored internally as BSON, binary JSON) that
can hold lists and nested objects, and that does not have to match the document next to it.


  SQL: FIXED COLUMNS                                                    MONGODB: FLEXIBLE DOCUMENT
                                                                        Every SQL row follows the same shape, so skills would need
    id             name                    city
                                                                        a second table and a join. A document keeps the list and the
    1              Asha                    Pune                         nested address inside the record itself (below).

    2              Ravi                    Delhi

--- PDF page 197 ---
one MongoDB document (Unit 3 Notes §6.1)


  {
       "_id": 1,
       "name": "Asha",
       "skills": ["Python", "React"],
       "address": { "city": "Pune" }
  }



 skills is a list (array) and address is a nested (embedded) object, both kept together in one record. Every
document gets a unique _id , which plays the role of the primary key. If you don't supply one, MongoDB gen‐
erates an ObjectId.


▸ Four kinds of NoSQL database

  Type                      Example                  Stores                              Good for

  Document                  MongoDB,                 JSON-like documents                 Apps, product catalogs, user profiles, content
                            CouchDB

  Key-value                 Redis,                   A value looked up by a key          Caching, sessions, leaderboards
                            DynamoDB

  Column (wide-             Cassandra,               Wide rows grouped by col‐           Huge volumes of logs, IoT/time-series writes
  column)                   HBase                    umn families

  Graph                     Neo4j                    Nodes and the links (edges)         Highly connected data: friends-of-friends, rec‐
                                                     between them                        ommendations, fraud rings



▸ SQL words and MongoDB words


      SQL               MongoDB                                                 Op        SQL                   MongoDB

      Database          Database                                                Create     INSERT INTO           insertOne({...})
                                                                                          ...
      Table             Collection (created on first insert)
                                                                                Read       SELECT * FROM         find({})
      Row               Document
                                                                                          ...
      Column            Field
                                                                                Update     UPDATE ...            updateOne(f,
      Primary key        _id                                                              SET                   {$set})

      JOIN              Embedding, or $lookup in                                Delete     DELETE FROM           deleteOne({...})
                        aggregation                                                       ...

      Fixed             Flexible (optional schema validation)
      schema

--- PDF page 198 ---
▸ CRUD in mongosh
 mongosh is MongoDB's interactive shell. Nothing has to be declared first: the collection appears when the first
document is inserted, and documents in it may have different fields. Open it inside the running container with
 docker compose exec mongo mongosh -u <user> -p <password> --authenticationDatabase admin .

           mongosh (Unit 3 Notes §6.4 + One-Shot Appendix)


  use appdb


  // Create
  db.events.insertOne({ action: "login", user: "asha", at: new Date() })
  db.events.insertMany([
       { action: "upload", user: "ravi", details: { filename: "slides.pdf", size_kb: 240 } },
       { action: "delete", user: "asha", reason: "duplicate" }
  ])


  // Read
  db.events.find({ action: "login" })                                      // WHERE action = 'login'
  db.students.find({ marks: { $gt: 60 } })                                   // marks > 60
  db.students.find({ "address.city": "Pune" })                               // nested field (dot + quotes)
  db.students.find({ skills: "Python" })                                     // array contains "Python"


  // Update: $set changes only the named field, the rest of the document stays
  db.events.updateOne({ action: "delete" }, { $set: { reason: "wrong course" } })


  // Count and delete
  db.events.countDocuments()
  db.products.deleteMany({ price: { $gt: 5000 } })
  db.events.deleteMany({})                                                   // empties the collection


The three events documents have different shapes: one has details , one has reason , one has neither. In SQL each would
need its own mostly-empty column.

 Operator               Meaning                 Operator             Meaning

  $eq     $ne           =,≠                      $set                set a field's value

  $gt     $gte          >,≥                      $inc                add to a number: {$inc: {views: 1}}

  $lt     $lte          <,≤                      $push               append to an array

  $in     $nin          in / not in a list       $unset              remove a field

  $and     $or          combine conditions       $lookup             join-like stage in aggregate()



▸ The A-Q1c query, written for MongoDB

           mongosh: top 5 above 75, and their average

--- PDF page 199 ---
db.students.find({ marks: { $gt: 75 } }, { _id: 0, name: 1, marks: 1 })                           // filter + projection
                 .sort({ marks: -1 })                                                                   // -1 = descending
                 .limit(5)


  db.students.aggregate([
       { $match: { marks: { $gt: 75 } } },                                           // like WHERE
       { $group: { _id: null, avgMarks: { $avg: "$marks" } } }                       // like AVG() over all rows
  ])




▸ Using MongoDB from Python (pymongo)

             activity.py (Unit 3 Notes §6.5)


  import os
  from datetime import datetime, timezone
  from pymongo import DESCENDING, MongoClient


  client = MongoClient(os.environ["MONGO_URL"], serverSelectionTimeoutMS=3000)
  events = client["appdb"]["events"]                            # database, then collection


  def log_event(action, user, details=None):
        events.insert_one({
              "action": action,
              "user": user,
              "details": details or {},
              "at": datetime.now(timezone.utc),
        })


  def recent_events(limit=20):
        # {"_id": 0} = projection: hide _id;              sort newest first
        return list(events.find({}, {"_id": 0}).sort("at", DESCENDING).limit(limit))


 MongoClient connects lazily, so a database that is down does not crash the program at import time. Activity logs fit MongoDB well:
each kind of event has its own shape, nothing else links to them, and they are written once and never edited. The course app keeps
core records in PostgreSQL and logs in MongoDB. Python method names use snake_case ( insert_one ), while mongosh uses
camelCase ( insertOne ).



▸ Modelling relationships: embed or reference?

             embedding vs referencing


  // EMBEDDING (denormalized): the order holds its items
  { _id: 501, customer: "Asha",
       items: [ { sku: "PEN", qty: 2 }, { sku: "INK", qty: 1 } ] }


  // REFERENCING (normalized): the post points at its author by _id

--- PDF page 200 ---
{ _id: 9, title: "Unit 3 notes", author_id: 101 }                               // posts collection
  { _id: 101, name: "Asha" }                                                      // authors collection




  EMBED WHEN…                                                              REFERENCE WHEN…
  the child belongs to one parent, is read together with it, and           the data is shared by many documents or grows without limit
  stays small (one-to-few). One read gets everything. A single             (one-to-many, many-to-many). Joining needs a second query
  document can be at most 16 MB.                                           or $lookup , and no foreign key enforces the link.



   ✏️ FILL IN THE BLANKS: MONGOSH AND PYMONGO
              blanks in code


     db.students.________({ name: "Asha", marks: 78 })                                      // add one document
     db.students.find({ marks: { ____: 60 } })                                                // marks greater than 60
     db.students.find({ "________.city": "Pune" })                                            // nested field
     db.students.updateOne({ name: "Asha" }, { ____: { marks: 85 } })
     db.students.________({ marks: { $lt: 40 } })                                             // remove all failing
     db.students.find().sort({ marks: ___ }).limit(3)                                         // top 3
     // Python:         client["appdb"]["events"].__________({"action": "login"})



   🔓 Answer key: insertOne · $gt · address · $set · deleteMany · -1 · insert_one


    3.11 Scaling, replication, sharding, BASE & CAP
📚 Sources: LEC 8 slide 16 (one line on scaling)    Unit 3 Notes §6.6 (one line)     Not in your files — added from standard references


    🚨 PARTLY MISSING · INSIDE A 10-MARK QUESTION · FINAL 2025-26 Q5(A)
    The question asks for "Scalability (vertical vs horizontal)" and "ACID properties vs BASE model". Your
    notes give one table row ("Mostly vertical (a bigger server)" vs "Horizontal (more servers)") and say NoSQL
    transactions are "looser by default". BASE, CAP, replication and sharding appear nowhere in your 22
    study files.

    Verdict: MUST LEARN. Two of the five bullets in a 10-mark question depend on it, and "ACID vs BASE"
    is a classic short question on its own.



▸ Vertical vs horizontal scaling
When an app grows (more users, more data), the database must handle more work. There are two ways to add
capacity.

--- PDF page 201 ---
Vertical scaling (scale UP)                                         Horizontal scaling (scale OUT)


                                                                                               router / load balancer


                                            64 GB RAM
                                          32 CPU · big SSD

                 4 GB                                                            server 1               server 2            server 3



                        same ONE server, made bigger                              MORE servers, work and data spread across them

                                             Scale up = bigger machine. Scale out = more machines.


                Vertical (scale up)                                                Horizontal (scale out)

 How            Add CPU, RAM and SSD to the one server                             Add more servers (nodes) and spread data and load
                                                                                   across them

 Limit          Hard ceiling: the biggest machine you can buy                      Practically unlimited: keep adding nodes

 Cost curve     Big machines get expensive fast                                    Many cheap commodity machines

 Failure        Single point of failure; resizing may need downtime                One node can fail and the others keep serving

 Complexity     Simple: the app does not change                                    Harder: data distribution, consistency, rebalancing

 Typical fit    Relational DBs: PostgreSQL, MySQL (joins and transactions          NoSQL: MongoDB, Cassandra, DynamoDB (designed
                like one machine)                                                  to be distributed)



  💡 THINK OF IT LIKE
  A busy restaurant. Vertical: replace the cook with a faster cook and buy a bigger stove, until no faster cook
  exists. Horizontal: open more counters with more cooks. You can keep adding them, but now orders must
  be split and the counters must stay in sync.



▸ Replication and sharding: the two tools of scaling out

  REPLICATION = COPIES                                                     SHARDING = SPLITTING

  The same data is copied to several servers. One                          The data is divided across servers by a shard
  primary takes writes and replicas (secondaries)                          key. For example, users with ids 1–1M go on
  copy it. Reads can be spread across replicas, and                        shard A and 1M–2M on shard B. Each shard holds
  if the primary dies a replica takes over (failover,                      only part of the data, so both storage and writes
  high availability). Replicas may lag a little behind,                    scale out. A router sends each query to the right
  which is where "eventual consistency" comes                              shard.
  from.                                                                    MongoDB: built-in sharded cluster (each shard is itself a
  MongoDB: replica set (1 primary + 2 or more secondaries).                replica set). PostgreSQL: partitioning on one server; true
  PostgreSQL: streaming replication / read replicas. AWS RDS:              sharding needs extensions such as Citus. A badly chosen

  read replicas, Multi-AZ.                                                 shard key creates "hot" shards.



This explains your notes' line "SQL scales mostly vertically, NoSQL horizontally". Joins and multi-row transac‐
tions are easy when all the data sits on one machine and hard when it is spread across many. Relational data‐
bases therefore usually grow up (and add read replicas), while document stores avoid joins by embedding and

--- PDF page 202 ---
were built to shard.


▸ ACID vs BASE
BASE is the design philosophy of many distributed NoSQL systems, the opposite trade-off to ACID:

    Basically Available: the system keeps answering requests even when some nodes fail.
    Soft state: the data on a replica may change over time without new input, as updates propagate.
    Eventual consistency: if writes stop, all replicas eventually agree. Until then, a read may return slightly old
    data.

                         ACID (relational: PostgreSQL)           BASE (distributed NoSQL)

  Stands for             Atomicity, Consistency, Isolation,      Basically Available, Soft state, Eventual consistency
                         Durability

  Priority               Correctness first                       Availability and scale first

  Consistency            Strong: every read sees the latest      Eventual: replicas converge after a short delay
                         committed write

  On failure / network   May refuse or wait rather than return   Keeps answering, possibly with stale data
  split                  wrong data

  Scaling                Mostly vertical                         Horizontal

  Example use            Bank transfer, stock levels, exam       Like counts, view counters, feeds, logs
                         results

  Examples               PostgreSQL, MySQL, Oracle               Cassandra, CouchDB, DynamoDB (default reads),
                                                                 MongoDB reading from secondaries



  ⚠️ DON'T OVERSTATE IT: MONGODB IS NOT "NO ACID"
  A single-document write in MongoDB is always atomic, and since version 4.0 (replica sets) and 4.2 (shard‐
  ed clusters) MongoDB supports multi-document ACID transactions. Reads from the primary are strongly
  consistent by default. It is "looser by default" (your notes' wording) because transactions are opt-in and
  cost performance, and because reading from secondaries is eventually consistent. Write this nuance for full
  marks.



▸ The CAP theorem (briefly)
In a distributed database, when a network partition (P) splits the nodes so they cannot talk, the system must
choose between:

    Consistency (C): every read gets the latest write, or an error.
    Availability (A): every request gets a (non-error) answer, possibly stale.

Partitions cannot be ruled out on real networks, so the practical choice is CP or AP. A single-server PostgreSQL
has no partition problem, which is why it can give full ACID.

--- PDF page 203 ---
Choice     Behaviour during a partition                  Examples                                             Good for

 CP         Refuses some requests to stay correct         MongoDB (single primary, default settings), HBase    Payments, inventory

 AP         Answers everything, reconciles later          Cassandra, CouchDB, DynamoDB (default)               Social feeds, carts, analytics



  🔑 MEMORY HOOK
  ACID = pessimist: "never be wrong, even if you must wait". BASE = optimist: "always answer, we'll fix it
  up in a moment". Chemistry helps too: acid and base sit at opposite ends of the scale.




    3.12 SQL vs NoSQL: choosing and comparing
📚 Sources: Unit 3 Notes §6.6         LEC 8 slides 16–17     Complete Revision deck slide 28    One-Shot Revision


Your notes and slides repeat one message: neither is better; pick the right tool, and justify the pick with a prop‐
erty of the data . Strict rules and relationships point to SQL. Varied shapes and heavy writes point to NoSQL.
Many real systems use both.

 Application                         Pick           Why (a property of the data)

 Banking app                         SQL            Money needs strict consistency and atomic transfers

 Chat app                            NoSQL          High volume of writes and flexible message shapes

 Student results                     SQL            Structured and relational (students, courses, marks)

 Product catalog                     NoSQL          Each product has different fields (a phone vs a shirt)

 Activity logs                       NoSQL          Massive writes, no joins, never edited



   PYQ       Final 2025-26 · Q5(A)   ★ LATEST                                                                                      10 M


  Compare SQL and NoSQL databases in detail. Explain how relational databases like PostgreSQL dif‐
  fer from document-based databases like MongoDB in terms of:
  - Data structure and schema
  - Scalability (vertical vs horizontal)
  - Query language and style
  - ACID properties vs BASE model
  - Relationships between data
  Use short examples to illustrate when each is better suited (e.g., banking vs social media).

   ✓   MODEL ANSWER: WRITE THIS

  SQL (relational) databases such as PostgreSQL store data in tables of rows and columns with a prede‐
  fined schema, link tables with keys, and are queried with SQL. NoSQL (non-relational) databases drop
  the fixed table and store data as documents, key-value pairs, wide columns or graphs. MongoDB is a doc‐
  ument database that stores JSON-like (BSON) documents in collections.

--- PDF page 204 ---
the same student, both ways


     -- PostgreSQL: rows in related tables
     students(id, name, dept_id → departments.id)           1 | Asha | 10
     student_skills(student_id, skill)                       (1,'Python') (1,'React')


     -- MongoDB: one document in the students collection
     { _id: 1, name: "Asha", dept: { id: 10, name: "CS" }, skills: ["Python", "React"] }



  1 · DATA STRUCTURE AND SCHEMA

  PostgreSQL: tables, rows and columns. The schema is fixed and defined up front (schema-on-write):
  CREATE TABLE fixes the columns and types, every row must match, and adding a field needs
    ALTER TABLE plus a migration. MongoDB: collections of documents that can contain nested objects and
  arrays. The schema is flexible: two documents in the same collection may have different fields, and new
  fields can be added at any time (optional JSON-schema validation exists). Example: a product catalog
  where a phone has ram and a shirt has size fits MongoDB naturally. In SQL it would need many mostly-
  NULL columns or extra tables.

  2 · SCALABILITY: VERTICAL VS HORIZONTAL

  PostgreSQL scales mainly vertically (scale up): a bigger server with more CPU, RAM and SSD, plus read
  replicas for reads. Splitting one relational database across many machines is hard because joins and trans‐
  actions then span servers. MongoDB scales horizontally (scale out): sharding splits a collection across
  many servers by a shard key, and replica sets keep copies for failover. Capacity grows by adding cheap
  machines. Vertical scaling has a hardware ceiling and a single point of failure; horizontal scaling has no
  practical ceiling but is more complex.

  3 · QUERY LANGUAGE AND STYLE

  PostgreSQL uses SQL: a standard, declarative language with powerful JOINs, GROUP BY, subqueries and
  aggregates, and the same syntax across MySQL and Oracle. MongoDB uses the MongoDB Query API
  (MQL): method calls that take JSON-style filter documents with operators such as $gt and $set , plus
  an aggregation pipeline ( $match → $group → $sort , $lookup for join-like steps). It is natural for devel‐
  opers working with JSON, but less suited to ad-hoc multi-table reporting.

              SQL


     SELECT name, marks FROM students WHERE marks > 75 ORDER BY marks DESC LIMIT 5;



              MongoDB (same question)


     db.students.find({ marks: { $gt: 75 } }, { name: 1, marks: 1 }).sort({ marks: -1 }).limit(5)



  4 · ACID PROPERTIES VS BASE MODEL
  PostgreSQL follows ACID: Atomicity (all-or-nothing, e.g. BEGIN…COMMIT/ROLLBACK), Consistency
  (constraints always hold), Isolation (concurrent transactions don't interfere) and Durability (committed data
  survives crashes). It favours strong consistency. NoSQL systems are built around BASE: Basically

--- PDF page 205 ---
Available, Soft state, Eventually consistent. They favour availability and partition tolerance (CAP theorem),
  and replicas may briefly return stale data. MongoDB sits in between: single-document writes are atomic
  and multi-document ACID transactions are supported (since v4.0), but they are opt-in and costlier, so it is
  "looser by default".

  5 · RELATIONSHIPS BETWEEN DATA

  PostgreSQL models relationships with foreign keys, which the database enforces (referential integrity),
  and combines tables with JOINs. Data is normalized, and many-to-many uses a junction table. MongoDB
  has no enforced foreign keys. Related data is either embedded (an order holds its items: one read, denor‐
  malized) or referenced by _id and combined with a second query or $lookup . Keeping the references
  valid is the application's job.

    Aspect                SQL (PostgreSQL)                                     NoSQL (MongoDB)

    Structure             Tables, rows, columns                                Collections of JSON/BSON documents

    Schema                Fixed, defined up front                              Flexible, can change any time

    Scaling               Mostly vertical (+ read replicas)                    Horizontal (sharding + replica sets)

    Query                 SQL, declarative, JOINs                              MQL methods + aggregation pipeline

    Consistency           ACID, strong                                         BASE-leaning, tunable; ACID transactions opt-in

    Relationships         FK + JOIN, enforced                                  Embed or reference, not enforced

    Best for              Banking, orders, ERP, results, reports               Social feeds, chat, catalogs, logs, IoT


  WHEN EACH IS BETTER SUITED

       Banking → SQL (PostgreSQL). A transfer debits one account and credits another. Both must happen
       or neither (atomicity), the balance must never be read wrong (strong consistency), and the data is regu‐
       lar and highly related (customer → accounts → transactions). FK constraints and SQL reporting are
       needed for audits.
       Social media → NoSQL (MongoDB). Posts, comments and likes arrive in huge volume. Content varies
       (text, images, polls, reels), so a flexible schema helps. A post can embed its recent comments for a one-
       read feed, and the system must scale across many servers. A like count that is a second out of date is
       acceptable (eventual consistency).

  Conclusion: neither is universally better. Choose by the data: strict, related, transactional data → SQL; var‐
  ied, high-volume, rapidly changing data → NoSQL. Many real systems use both (polyglot persistence). The
  course's Student Notes App keeps users and notes in PostgreSQL and activity logs in MongoDB.

  🎯 Marking scheme guess: 1 M definitions + diagram · 1.5 M × 5 aspects (schema, scaling, query, ACID/BASE, relationships) = 7.5 M · 1.5
  M banking vs social-media justification + conclusion




    3.13 Django's ORM with SQL and with NoSQL
📚 Sources: Unit 2 Notes §4.4, §6       LEC 4 (Python · Django)       One-Shot Revision (ORM)

 Not in your files — added from standard references (MongoDB part)

--- PDF page 206 ---
🚨 NOT IN YOUR STUDY MATERIAL · 6 MARKS · FINAL 2025-26 Q5(B)
    Your files teach the Django ORM against SQLite and PostgreSQL (Unit 2 §4.4 and §6) and raw SQL with
    placeholders (§6.4). No file explains how Django works (or doesn't) with MongoDB: djongo,
    MongoEngine and the official django-mongodb-backend are never mentioned, and neither are the ORM
    vs raw-query trade-offs as a comparison.

    Verdict: MUST LEARN. 6 marks in the newest paper, and this kind of "integration trade-off" question is
    the new examiner's style. Learn the four points below and the model answer.



▸ Recap: what an ORM is
An ORM (Object-Relational Mapper) lets you work with database rows as Python objects. You write
 Student.objects.filter(marks__gt=75) and Django's database backend compiles it into SQL for the con‐
figured database. Django ships official backends only for relational databases: PostgreSQL, MySQL/MariaDB,
SQLite and Oracle.

                 models.py      →                migration file    →          SQL DDL
                                                                                            →
                                                                                                     real table
                 Python class   makemigrations   0001_initial.py   migrate   CREATE TABLE          school_student




▸ How Django models become relational tables

           school/models.py


  from django.db import models


  class Department(models.Model):
        name = models.CharField(max_length=50, unique=True)


  class Student(models.Model):
        name    = models.CharField(max_length=80)
        email = models.EmailField(unique=True)
        marks = models.IntegerField(default=0)
        dept    = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True)


        def __str__(self):
             return self.name



           python manage.py sqlmigrate school 0001 (PostgreSQL output, simplified)


  CREATE TABLE "school_department" (
        "id"      bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        "name" varchar(50) NOT NULL UNIQUE);
  CREATE TABLE "school_student" (
        "id"            bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
        "name"          varchar(80) NOT NULL,
        "email"         varchar(254) NOT NULL UNIQUE,

--- PDF page 207 ---
"marks"         integer NOT NULL,
        "dept_id" bigint NULL);
  ALTER TABLE "school_student" ADD CONSTRAINT "school_student_dept_id_..._fk"
        FOREIGN KEY ("dept_id") REFERENCES "school_department" ("id");
  CREATE INDEX "school_student_dept_id_..." ON "school_student" ("dept_id");



 Django side                                Becomes in the relational database

 Model class Student in app school          Table school_student

 Field attribute                            Column with a type ( varchar(80) ); IntegerField → integer,
 ( CharField(max_length=80) )                DecimalField → numeric, DateTimeField → timestamp

 Automatic id                               Auto-increment primary key (identity column)

  unique=True , null=False                  UNIQUE and NOT NULL constraints

  ForeignKey(Department)                    Column dept_id + FOREIGN KEY constraint + index

  ManyToManyField(Course)                   A hidden junction table school_student_courses(student_id,
                                            course_id)

 An instance + .save() / .delete()          One row: INSERT or UPDATE / DELETE

 QuerySet filter() , order_by() ,           SELECT … WHERE … ORDER BY … LIMIT
 slicing

  filter(dept__name="CS") , selec‐          An SQL JOIN
 t_related("dept")

  transaction.atomic()                      BEGIN … COMMIT / ROLLBACK


            python manage.py shell: the A-Q1c queries through the ORM


  from django.db.models import Avg
  top5 = Student.objects.filter(marks__gt=75).order_by("-marks")[:5]
  print(top5.query)          # SELECT ... WHERE "school_student"."marks" > 75 ORDER BY ... DESC LIMIT 5
  Student.objects.filter(marks__gt=75).aggregate(Avg("marks"))                   # {'marks__avg': 85.28...}




▸ Why NoSQL integration is more complex

 1         The ORM speaks SQL. Its query compiler produces SQL text, and Django core has no MongoDB
           backend. Something must translate QuerySets into MongoDB's query/aggregation language, or you
           must use a different library.

 2         No joins. ForeignKey traversal ( dept__name ), select_related and many-to-many all assume JOINs.
           MongoDB has only $lookup (slower, limited) and expects you to embed instead.

 3         Migrations assume a schema. Django migrations are DDL (CREATE/ALTER TABLE). A schemaless col‐
           lection has nothing to alter, so migrations become partial (collections and indexes only), and old docu‐
           ments keep their old shape.

--- PDF page 208 ---
4        Constraints and transactions. FK integrity is not enforced by MongoDB. Multi-document transactions
          need a replica set and do not map one-to-one to atomic() .

 5        Ecosystem assumptions. admin, auth, sessions, contenttypes and most third-party apps assume inte‐
          ger PKs and relational features. MongoDB uses ObjectId keys, so URL patterns like <int:id> and
          many apps need changes.


▸ The ways to use Django with MongoDB

                                                    Keeps Django models /
 Option                 What it is                                                   Status / catch
                                                    admin?

 djongo                 A backend that translates   Partly                           Effectively unmaintained (no release since
                        Django's generated SQL                                       2021), tied to old Django versions, incomplete
                        into MongoDB queries                                         translation. Avoid for new projects

 MongoEngine            A separate ODM (Object-     No: no admin, ModelForm or       Mature and maintained; good support for em‐
                        Document Mapper): you       migrations; DRF needs an extra   bedded documents and lists
                        write Document class‐       package
                        es, not models.Model

 django-mon‐            MongoDB Inc.'s official     Mostly yes (admin and auth via   New. ObjectId primary keys; Django's own
 godb-backend           Django database backend;    MongoDB-specific app configs      atomic() is a no-op (use the backend's
                        generally available since   and migrations); adds             transaction.atomic() , which needs a
                        Sept 2025                    EmbeddedModelField ,            replica set); some QuerySet methods
                                                     ArrayField                      ( raw() , prefetch_related() , ex‐
                                                                                     tra() ) unsupported

 pymongo beside         ORM stays on                Yes, for the SQL data            Simple and full control, but no ORM features for
 the ORM (course        PostgreSQL; MongoDB is                                       the Mongo data. This is how Unit 3 Notes §6.5
 way)                   used directly through the                                    logs events
                        driver


           MongoEngine: a Document, not a Model


  import os
  from mongoengine import (connect, Document, EmbeddedDocument, StringField,
                                     IntField, ListField, EmbeddedDocumentField)


  connect(db="appdb", host=os.environ["MONGO_URL"])


  class Address(EmbeddedDocument):
        city = StringField()


  class Student(Document):                                    # not models.Model: no admin, no migrations
        name       = StringField(required=True, max_length=80)
        marks      = IntField(min_value=0, max_value=100)
        skills     = ListField(StringField())
        address = EmbeddedDocumentField(Address)

--- PDF page 209 ---
Student(name="Asha", marks=92, skills=["Python"], address=Address(city="Pune")).save()
  Student.objects(marks__gt=75).order_by("-marks").limit(5)



             django-mongodb-backend: settings.py


  DATABASES = {
        "default": {
              "ENGINE": "django_mongodb_backend",
              "HOST": "mongodb://user:pass@mongo:27017/",
              "NAME": "appdb",
        },
  }
  DEFAULT_AUTO_FIELD = "django_mongodb_backend.fields.ObjectIdAutoField"              # ObjectId, not int ids
  # admin / auth / contenttypes need the Mongo-specific AppConfigs and
  # MIGRATION_MODULES from the backend's project template




▸ Trade-offs of Django + MongoDB

  YOU GAIN                                                   YOU LOSE / PAY

       Flexible schema: add fields without ALTER                  Joins, select_related and cross-relation
       TABLE                                                      lookups (limited or slow)
       Nested data (arrays, embedded docs) that                   Enforced foreign keys and full migrations
       maps directly to JSON APIs                                 Admin/auth/third-party compatibility (needs
       Horizontal scaling and fast writes for logs,               special configs, or is lost with MongoEngine)
       events and feeds                                           Simple atomic() transactions; a smaller,
                                                                  younger ecosystem



▸ ORM vs raw queries

             same query three ways


  # 1) ORM
  Student.objects.filter(marks__gt=75).order_by("-marks")[:5]


  # 2) Raw SQL mapped back to model objects
  Student.objects.raw(
        "SELECT id, name, marks FROM school_student WHERE marks > %s ORDER BY marks DESC LIMIT 5",
  [75])


  # 3) Raw cursor (Unit 2 Notes §6.4): plain tuples back
  from django.db import connection
  with connection.cursor() as cursor:
        cursor.execute("SELECT AVG(marks) FROM school_student WHERE marks > %s", [75])
        avg = cursor.fetchone()[0]

--- PDF page 210 ---
ORM                                                                Raw SQL

 Advantage      Database-independent and Pythonic; automatically parame‐           Full control; can use DB-specific features (window
                terised (safe from SQL injection); works with migrations, forms,   functions, CTEs, full-text search); can be hand-
                admin and DRF; less code                                           tuned for speed

 Limitation     Less control over the exact SQL; complex reports are awkward;      Tied to one database dialect; you must use place‐
                can hide inefficiency (the N+1 query problem when selec‐           holders yourself; results may not be model objects;
                t_related is forgotten)                                            harder to maintain



   PYQ        Final 2025-26 · Q5(B)   ★ LATEST                                                                                  6M


  Discuss how Django's ORM interacts differently with SQL and NoSQL systems. Explain conceptually:
  - How Django models translate to relational tables
  - Why integration with NoSQL databases can be more complex
  - What trade-offs exist when using Django with MongoDB
  - One advantage and one limitation of using ORM vs raw queries

   ✓   MODEL ANSWER: WRITE THIS

  Django's ORM (Object-Relational Mapper) was designed for relational databases. Its official backends
  (PostgreSQL, MySQL, SQLite, Oracle) compile Python QuerySets into SQL. With a NoSQL database like
  MongoDB it needs a third-party or separate layer.

  1. Models → relational tables. Each model class becomes a table ( app_model , e.g. school_student ),
  each field becomes a typed column ( CharField(max_length=80) → varchar(80) ), an auto id be‐
  comes the primary key, unique=True becomes a UNIQUE constraint, ForeignKey becomes a dept_id
  column with a FOREIGN KEY constraint, and ManyToManyField becomes a junction table.
    makemigrations writes the change and migrate runs the CREATE/ALTER TABLE. Each object is a row,
  and Student.objects.filter(marks__gt=75) becomes SELECT … WHERE marks > 75 .

  2. Why NoSQL integration is more complex. (a) Django has no built-in MongoDB backend, so QuerySets
  must be translated into MongoDB queries. (b) Relations rely on JOINs ( select_related , dept__name ),
  and MongoDB has none, only embedding or $lookup . (c) Migrations are schema DDL, but collections are
  schemaless. (d) FK integrity and atomic() transactions don't map directly. (e) admin/auth and third-party
  apps assume integer keys and relations, while MongoDB uses ObjectId.

  3. Trade-offs with MongoDB. Options: djongo (SQL-to-Mongo translator, now unmaintained),
  MongoEngine (its own ODM: Document classes, so you lose the Django admin, ModelForms and migra‐
  tions) and the official django-mongodb-backend (GA 2025; keeps most of Django, but needs ObjectId keys
  and its own transaction API, and some QuerySet features are missing). Gain: flexible schema, nested docu‐
  ments, horizontal scaling and fast writes. Lose: joins, enforced relations, full migrations, simple transactions
  and some ecosystem compatibility. A common compromise is PostgreSQL through the ORM for core data
  plus pymongo for logs, as in the course app.

  4. ORM vs raw queries. Advantage: the ORM is database-independent and automatically parameterises
  values, which prevents SQL injection, so less and safer code. Limitation: less control and possible ineffi‐
  ciency for complex queries (e.g. the N+1 problem, or window functions and reports that are easier in raw
  SQL via Model.objects.raw() or connection.cursor() ).

--- PDF page 211 ---
🎯 Marking scheme guess: 1.5 M model → table mapping · 1.5 M reasons NoSQL is harder · 2 M Mongo trade-offs (+ naming an integra‐
  tion option) · 1 M one ORM advantage + one limitation




    3.14 File storage with AWS S3
📚 Sources: Unit 3 Notes §7         LEC 8 slides 18–19     Complete Revision deck slide 29    One-Shot Revision



▸ Why files do not belong in the database
Users upload photos, PDFs and videos. Storing the file itself in a database column (a BLOB) is a poor idea.
Large files make the database huge, which slows queries and backups, and database storage costs more than
storage built for files. The better design splits the job: the file goes to object storage (S3), and only a short refer‐
ence to it (its key or URL) goes to the database .

 Files inside the database                                                File in S3, key in the database

 Database grows very large                                                Database stays small

 Slow queries and slow backups                                            Fast queries and simple backups

 Costly storage                                                           Cheap storage built for files


Example: the students row holds photo_key = 'profile/asha.jpg' , and the photo itself sits in the bucket
under that name.


▸ Buckets, objects and keys
Amazon S3 (Simple Storage Service) is AWS's object storage service. It has no real folders and no tables,
only three ideas:

 Term       Meaning                                                                                                  Example

 Bucket     A named container for objects. The name is globally unique, and the bucket lives in one region            notes-app-media

 Object     One stored file plus its metadata (type, size, date). Up to 5 TB each                                    the photo

 Key        The object's full name inside the bucket. The slashes only look like folders                              profile/asha.jpg



  MEDIA                                            BACKUPS                                          STATIC SITES
  Profile photos, uploads                          Database dumps                                   The files of a React build ( in‐
  ( notes/unit3.pdf )                              ( backups/db.sql )                               dex.html , JS, CSS)


 Storage                                                                                    AWS /
                  What it is                                                                                         Use
 kind                                                                                       DigitalOcean

 Object           Files with keys, accessed over an HTTP API, flat namespace, near-         S3 / Spaces              Media, backups, static
                  unlimited size                                                                                     sites

 Block            A raw virtual disk attached to one server                                 EBS / Volumes            OS disk, database data
                                                                                                                     files

--- PDF page 212 ---
Storage                                                                             AWS /
                  What it is                                                                                Use
 kind                                                                                DigitalOcean

 File             A shared file system with real folders                             EFS / NFS              Shared drives across
                                                                                                            servers


Extra facts that impress examiners: S3 is designed for 99.999999999% ("eleven nines") durability. Storage classes trade price for
access speed: S3 Standard (frequent use), Standard-IA (infrequent access) and Glacier (archives). Versioning keeps old copies, and
lifecycle rules move or delete objects automatically.


▸ Access control: private by default
      Public vs private bucket. A private bucket is the safe default. New buckets have Block Public Access
      switched on. Make objects public only for things like a static website.
      IAM (Identity and Access Management) rules say which user or service may do what, e.g. "the web app may
        PutObject and GetObject on notes-app-media , nothing else". A bucket policy sets the same kind of
      rule on the bucket itself.
      Presigned URL: when a user needs a private file, the app generates a temporary link that carries a signa‐
      ture and an expiry time. It works with no password until it expires (e.g. 300 s), then gives AccessDenied.
      Credentials (access key and secret) live in environment variables, never in code.


▸ Using S3 from Python (boto3)

            storage.py (Unit 3 Notes §7.3)


  import boto3


  s3 = boto3.client(
         "s3",
         endpoint_url="http://localhost:9000",                  # leave this line out to use real AWS S3
         aws_access_key_id="<access-key>",                      # from env vars in real code
         aws_secret_access_key="<secret-key>",
         region_name="us-east-1",
  )


  s3.create_bucket(Bucket="app-media")


  with open("asha.jpg", "rb") as f:                                           # rb = read bytes
         s3.upload_fileobj(f, "app-media", "profile/asha.jpg")                  # (file, bucket, key)


  url = s3.generate_presigned_url(
         "get_object",
         Params={"Bucket": "app-media", "Key": "profile/asha.jpg"},
         ExpiresIn=300,                                                         # seconds
  )

--- PDF page 213 ---
then store only the key in PostgreSQL


  UPDATE students SET photo_key = 'profile/asha.jpg' WHERE id = 1;



 1        User uploads the file to the Django app (form or API).

 2        App stores the file in the bucket under a key ( upload_fileobj ).

 3        App stores the key in PostgreSQL ( photo_key column).

 4        Later, to show it, the app reads the key and returns a presigned URL. The browser downloads straight
          from S3.


   ⚠️ THE PRESIGNED-URL HOST TRAP (FROM YOUR NOTES)
   A presigned URL is signed for a specific host name. Inside the Compose network the app reaches storage
   as http://storage:9000 , but a browser cannot resolve storage . A link signed with the internal address
   will not work in the browser, so the deployed app signs links with the public address
   ( S3_PUBLIC_ENDPOINT=http://<droplet-ip>:9000 ). Opening a private object's plain URL without a signa‐
   ture gives AccessDenied.


S3-compatible servers: many storage products copy the S3 API, so the same boto3 code works if you just change endpoint_url :
DigitalOcean Spaces, MinIO, and RustFS (the container your Unit 3 lab uses). In Django, the django-storages package makes
every FileField / ImageField upload go to S3 automatically, and the model's column stores the file's name (key), which is ex‐
actly the "key in the DB" rule.


   ✏️ FILL IN THE BLANKS: S3
               blanks in code


      import ______
      s3 = boto3.______("s3")
      s3.______(Bucket="app-media")
      with open("notes.pdf", "rb") as f:
           s3.______(f, "app-media", "notes/unit3.pdf")
      link = s3.______("get_object", Params={"Bucket": "app-media", "Key": "notes/unit3.pdf"},
      ______=600)



     1. The database stores the                        ; S3 stores the                    .
     2. A bucket +                    uniquely identify an object.
     3. Who-can-do-what rules on AWS are written in                                .

   🔓 Answer key: boto3 · client · create_bucket · upload_fileobj · generate_presigned_url · ExpiresIn · 1) key (or URL); file · 2) key · 3)
   IAM (policies)

--- PDF page 214 ---
3.15 Cloud service models: IaaS, PaaS, SaaS
📚 Sources: Unit 3 Notes §8.1         LEC 8 slide 20   Complete Revision deck slide 29   One-Shot Revision


Cloud computing is the on-demand delivery of computing resources (servers, storage, databases, networking
and software) over the internet with pay-as-you-go pricing, instead of buying and running your own hardware.
Its standard characteristics are on-demand self-service, broad network access, resource pooling, rapid elasticity
(scale up or down in minutes) and measured service (you pay for what you use).

Running an app needs a stack of layers: physical servers and network → operating system → runtime (e.g.
Python) → application and data. A service model says how many layers the provider manages and how many
you still manage. The more the provider manages, the less control you have.

  Layer                 On-premise         IaaS                           PaaS                                 SaaS

  Application           You                You                            You                                  Provider
  and data

  Runtime               You                You                            Provider                             Provider

  Operating             You                You                            Provider                             Provider
  system

  Servers and           You                Provider                       Provider                             Provider
  network

  Example               Your own           DigitalOcean Droplet           Heroku                               Gmail
  (notes)               server room

  More                  College data       AWS EC2, Azure VMs,            DO App Platform, AWS Elastic         Google Docs, Zoom,
  examples              centre             Google Compute Engine          Beanstalk, Google App Engine,        Salesforce, Office 365
                                                                          Render

  Pizza analogy         Make it at         Take and bake                  Delivered                            Dine out
                        home



  💡 THINK OF IT LIKE (THE COURSE'S PIZZA)
  On-premise: you buy the oven, the dough and the toppings, and you bake. IaaS: you rent the kitchen and
  oven, but you still bring the ingredients and do the baking ("take and bake"). PaaS: you choose the pizza
  and it is baked and delivered; you only decide the recipe (your code). SaaS: you sit in the restaurant and
  eat.



▸ IaaS for software developers (syllabus line)
Infrastructure as a Service (IaaS) provides virtualised computing infrastructure (virtual machines, block stor‐
age, networking such as public IPs, firewalls, private networks and load balancers) on demand over the internet.
You provision it in minutes through a web console, a CLI ( doctl , aws ) or an API, and pay by usage. The
provider manages the physical hardware, data centre, virtualisation and network. You manage the OS (up‐
dates, security), runtime, middleware, application and data.

--- PDF page 215 ---
ADVANTAGES                                                                   DISADVANTAGES

        Full control: any OS, any software, root access                            You do the sysadmin work: patching, firewall,
        No hardware to buy; pay only for what runs                                 backups, monitoring

        Scale in minutes (resize, add servers)                                     Misconfiguration risk (open ports, weak SSH)

        Global regions close to your users                                         Needs Linux/DevOps skills

        Ideal for custom stacks, e.g. Docker Compose                               Costs grow if machines are left running
        deployments


Other models you may name: FaaS / serverless (AWS Lambda, DO Functions): you upload one function and the provider runs it per re‐
quest. Deployment models: public cloud (AWS, DO), private cloud (one organisation's own) and hybrid (both).


  ✍️ 5-MARK "EXPLAIN IAAS / PAAS / SAAS"
  Definition of cloud computing (1 line) → the who-manages-what table → one example each (Droplet,
  Heroku, Gmail) → pizza analogy → one line: "a DigitalOcean droplet is IaaS: you get the server and manage
  everything above the hardware".




    3.16 AWS and its core services
📚 Sources: Unit 3 Notes §7 (S3 + IAM only)        LEC 8 slides 18–19        LEC 6 (Docker) mentions AWS in passing

 Not in your files — added from standard references (other services)



    🚨 NOT IN YOUR STUDY MATERIAL · 20 MARKS · RE-EXAM 2023-24 Q4(B) + FINAL 2024-25
      Q4(A)

    "What is AWS? Explain any 5 AWS services" was asked for 10 marks in two of the three papers. Your
    files cover only S3 (plus one line on IAM inside the S3 section). They never define AWS, and EC2, RDS,
    Lambda, DynamoDB, CloudFront, Route 53, VPC, Elastic Beanstalk, CloudWatch and SageMaker are
    missing.

    Verdict: MUST LEARN. It is a free 10 marks if it appears again, and the answer is pure recall. Learn the
    definition, the five core services (EC2, S3, RDS, Lambda, IAM) in detail, and the rest in one line each.



▸ What AWS is
Amazon Web Services (AWS) is Amazon's cloud computing platform. It offers more than 200 on-demand ser‐
vices (compute, storage, databases, networking, security, analytics and machine learning) over the internet with
pay-as-you-go pricing. It started in 2006 with S3 and EC2 and is the largest public cloud provider. Instead of
buying servers, a company rents exactly what it needs, by the second or by the request, and releases it when
done.

 Concept                Meaning

 Region                 A geographic area with its own cluster of data centres, e.g. ap-south-1 (Mumbai), ap-south-2 (Hyder‐
                        abad), us-east-1 (N. Virginia). Pick the one near your users (latency) or required by law (data residency)

--- PDF page 216 ---
Concept                Meaning

 Availability           One or more isolated data centres inside a region, with independent power and networking. Running across 2+ AZs
 Zone (AZ)              survives one data centre failing (high availability)

 Edge location          A small site in many cities where CloudFront caches content close to users

 Pay-as-you-go          No upfront cost; billed per second/hour, per GB or per request. A free tier lets beginners try many services

 Shared                 AWS secures the cloud (hardware, facilities, network). You secure what you put in the cloud (data, IAM users, OS
 responsibility         patches on EC2, open ports)

 Ways to use it         Management Console (web), AWS CLI, SDKs (boto3 for Python, as in 3.14), infrastructure-as-code
                        (CloudFormation)



▸ The service catalogue: what, when, and where in our app

                                                                                                            In our Django + React notes
 Service           Category              What it is                               Typical use
                                                                                                            app

 EC2               Compute               Virtual servers ("instances") you rent   Run any server            Runs Django + gunicorn + nginx
                   (IaaS)                and fully control                        software                  (AWS's version of a droplet)

 S3                Storage               Object storage: buckets, objects,        Media, backups, sta‐      Profile photos and notes PDFs;
                                         keys                                     tic sites                 the React build; pg_dump
                                                                                                            backups

 RDS               Database              Managed relational DB (PostgreSQL,       Production SQL            Django's HOST = the RDS end‐
                                         MySQL, MariaDB, Oracle, SQL              without being a DBA       point instead of the db
                                         Server; Aurora)                                                    container

 Lambda            Compute               Runs your function on an event, with     Event processing,         Make a thumbnail whenever a
                   (serverless)          no server to manage; pay per call        small APIs, cron jobs     photo lands in S3

 IAM               Security              Users, groups, roles and JSON poli‐      Least-privilege           A role that lets the EC2 app only
                                         cies: who can do what                    access                    read/write the app-media
                                                                                                            bucket

 DynamoDB          Database              Fully managed key-value / document       Sessions, carts,          Activity log (AWS-native alterna‐
                   (NoSQL)               DB, millisecond latency at any scale     leaderboards              tive to our MongoDB container)

 CloudFront        Networking            Content delivery network: caches         Fast global static        Serves the React build and im‐
                   (CDN)                 content at edge locations, HTTPS         content                   ages from S3 near each user

 Route 53          Networking            Managed DNS + domain registration        Map domain →               notesapp.in → CloudFront /
                   (DNS)                 + health-checked routing                 server                    load balancer

 VPC               Networking            Your private, isolated network in AWS:   Keep databases off        EC2 in a public subnet, RDS in a
                                         subnets, route tables, security groups   the internet              private one ("databases publish
                                                                                                            no ports")

 Elastic           PaaS                  Upload code; AWS creates EC2, load       Deploy without             eb deploy the Django app
 Beanstalk                               balancer, scaling and monitoring for     server admin              (Heroku-style)
                                         you

 CloudWatch        Monitoring            Metrics, logs, alarms, dashboards for    Observe and alert         Alarm when EC2 CPU > 80% or
                                         all services                                                       5xx errors spike

 SageMaker         Machine               Build, train and deploy ML models as     ML at scale               Host the Iris model from Unit 2 as
                   learning              managed endpoints                                                  an endpoint Django calls

--- PDF page 217 ---
Also worth one line: ECR/ECS/EKS (store and run Docker images and Kubernetes; see the Unit 5 chapter), SNS/SQS (notifications and
queues), Cognito (user sign-in).


                                                                VPC · region ap-south-1 (Mumbai) · spread over 2 AZs
                               Route 53
                                     DNS                          public subnet                                private subnet (no internet access)


                                                                             Load balancer
                                                         /api                                                            RDS PostgreSQL
         Users                CloudFront                                                                                 Multi-AZ · auto backups
         browser              CDN + HTTPS
                                                                                                         SQL
                                                                                EC2 · Django
                                                                           gunicorn · Auto Scaling

                                          static files




                                     S3                          Lambda                 DynamoDB            CloudWatch                         IAM
                           React build · media              runs on S3 upload             activity log      metrics · alarms              roles · policies



 A typical AWS layout for the course app: Route 53 → CloudFront → (S3 for the React build) or (load balancer → EC2 Django → RDS in a private
                                                         subnet). Regional services are along the bottom.



▸ Our DigitalOcean / Compose stack, translated to AWS

 Course stack (Unit 3 Notes §9)                      AWS managed equivalent

 Droplet (VPS)                                       EC2 instance

  db container (postgres:16)                         RDS for PostgreSQL

  mongo container                                    DynamoDB, Amazon DocumentDB (MongoDB-compatible), or MongoDB Atlas running on
                                                     AWS

  storage container (S3-                             S3 itself
 compatible)

 nginx as single entrance                            Application Load Balancer + CloudFront

 Droplet firewall / VPC                              Security groups / VPC

 Droplet backups and snapshots                       EBS snapshots, AWS Backup, RDS automated backups

 DigitalOcean App Platform (PaaS)                    Elastic Beanstalk / App Runner



   PYQ       Final 2024-25 · Q4(a)          Re-Exam 2023-24 · Q4(b)                                                                             10 M each


  What is AWS? Explain any 5 AWS services that you are familiar with.

   ✓   MODEL ANSWER: WRITE THIS


  WHAT IS AWS

  Amazon Web Services (AWS) is a cloud computing platform from Amazon that provides more than 200
  on-demand IT services (computing power, storage, databases, networking, security, analytics and machine
  learning) over the internet on a pay-as-you-go basis. Organisations rent resources in minutes instead of
  buying and maintaining physical servers. AWS runs in Regions around the world (e.g. Mumbai
    ap-south-1 ), each with multiple isolated Availability Zones for fault tolerance.

--- PDF page 218 ---
Features: on-demand self-service · elastic (auto) scaling · pay only for usage, with a free tier · global reach
  (regions, AZs, edge locations) · high availability and durability · security (IAM, encryption, compliance) under
  a shared-responsibility model · access via console, CLI and SDKs (boto3).

                                                                  EC2              RDS               S3
                  Users   →   Route 53 / CloudFront    →     Django app
                                                                          →     PostgreSQL
                                                                                              +      files



  1 · AMAZON EC2 (ELASTIC COMPUTE CLOUD): COMPUTE

  Provides resizable virtual servers (instances) in the cloud: IaaS. You choose an AMI (OS image, e.g.
  Ubuntu), an instance type (vCPU/RAM, e.g. t3.micro ), storage (EBS volumes), a security group (firewall
  rules) and a key pair for SSH. Pricing: On-Demand, Reserved/Savings Plans (cheaper for 1–3 year commit‐
  ment) and Spot (spare capacity, up to ~90% cheaper). Auto Scaling adds or removes instances with load.
  Use: hosting web apps and APIs, e.g. running our Django + gunicorn + nginx server.

  2 · AMAZON S3 (SIMPLE STORAGE SERVICE): STORAGE

  Object storage for any amount of data. Files are objects stored in buckets and identified by a key
  ( profile/asha.jpg ). It is designed for 99.999999999% durability, has storage classes (Standard,
  Infrequent Access, Glacier), versioning, static-website hosting, and private-by-default access with
  IAM/bucket policies and presigned URLs. Use: user uploads, backups, hosting the React build. The data‐
  base keeps only the key.

  3 · AMAZON RDS (RELATIONAL DATABASE SERVICE): DATABASE

  A managed relational database: PostgreSQL, MySQL, MariaDB, Oracle, SQL Server and Amazon Aurora.
  AWS handles installation, patching, automated backups with point-in-time restore, Multi-AZ standby for
  automatic failover, and read replicas for scaling reads. You just connect with an endpoint. Use: the produc‐
  tion PostgreSQL for a Django app ( HOST = mydb.xxxx.ap-south-1.rds.amazonaws.com ).

  4 · AWS LAMBDA: SERVERLESS COMPUTE

  Runs your code as functions triggered by events (an S3 upload, an HTTP call through API Gateway, a
  schedule) without provisioning servers. It scales automatically from zero to thousands of calls, and you
  pay only per request and compute time (each run can last up to 15 minutes). Supports Python, Node.js,
  Java and more. Use: generate a thumbnail whenever an image is uploaded to S3.

              lambda_function.py


     def lambda_handler(event, context):                # AWS calls this on every S3 upload event
           for record in event["Records"]:
                key = record["s3"]["object"]["key"]
                print("New upload:", key)                # e.g. create a thumbnail here
           return {"statusCode": 200}



  5 · AWS IAM (IDENTITY AND ACCESS MANAGEMENT): SECURITY

  Controls who can access which AWS resources and what they can do. It has users (people/apps),
  groups, roles (temporary permissions for services such as an EC2 instance) and policies (JSON docu‐
  ments that Allow or Deny actions on resources). Best practices: least privilege, MFA, never use the root ac‐

--- PDF page 219 ---
count daily, and use roles instead of hard-coded keys. IAM itself is free. Use: allow the web server to read
  and write only one S3 bucket.

              policy.json: least privilege for the app


     {
         "Version": "2012-10-17",
         "Statement": [{
            "Effect": "Allow",
            "Action": ["s3:GetObject", "s3:PutObject"],
            "Resource": "arn:aws:s3:::app-media/*"
         }]
     }


  Other valid choices (one line each if you prefer them): DynamoDB (managed NoSQL), CloudFront (CDN), Route 53 (DNS), VPC
  (private network), Elastic Beanstalk (PaaS deploy), CloudWatch (monitoring), SageMaker (ML).

  Conclusion: AWS lets a developer build a complete, scalable and secure application without owning hard‐
  ware: EC2 or Lambda for compute, S3 for files, RDS or DynamoDB for data, and IAM to lock it all down,
  paying only for what is used.

  🎯 Marking scheme guess: 2 M definition + features (regions/AZ, pay-as-you-go) · 1.5 M × 5 services (what + 2 features + use case) = 7.5
  M · 0.5 M diagram / conclusion




  🔑 MEMORY HOOK: THE FIVE TO ALWAYS WRITE
  "E-S-R-L-I": EC2 runs it, S3 stores files, RDS stores rows, Lambda reacts to events, IAM decides who's al‐
  lowed. One per category: compute, storage, database, serverless, security.




    3.17 DigitalOcean and droplets
📚 Sources: Unit 3 Notes §8.2       LEC 8 slides 21–22    One-Shot Revision     Complete Revision deck slide 29


DigitalOcean (DO) is a cloud provider (founded 2011, New York) known for developer-friendly simplicity and
predictable pricing. It is aimed at developers, students, startups and small businesses. It is a paid service and
not open source, although it runs open-source software such as Ubuntu and PostgreSQL.

 DO product                                             What it is                                                        Model

 Droplets                                               Virtual private servers (Linux VMs)                               IaaS

 Volumes                                                Extra block storage (SSD disks) attached to a droplet             IaaS

 Spaces                                                 S3-compatible object storage + built-in CDN                       Storage

 Managed Databases                                      PostgreSQL, MySQL, MongoDB, Redis/Valkey run for you              DBaaS

 App Platform                                           Push code from GitHub; DO builds and runs it                      PaaS

 Kubernetes (DOKS)                                      Managed Kubernetes clusters for containers                        Containers

--- PDF page 220 ---
DO product                                           What it is                                                        Model

 Load Balancers · Cloud Firewalls · VPC ·             Spread traffic · restrict ports · private network · graphs and    Networking /
 Monitoring                                           alerts                                                            ops

 Functions                                            Serverless functions                                              FaaS



▸ What a droplet is
A droplet is DigitalOcean's name for a virtual private server (VPS): a Linux-based virtual machine that runs on
DO's physical hardware and behaves like your own computer in the cloud. It has its own public IP address, root
access, a chosen amount of CPU, RAM and SSD, and is ready in about a minute. Because you get the raw
server and manage everything above the hardware, a droplet is IaaS.

  💡 THINK OF IT LIKE (YOUR NOTES' ANALOGY)
  Renting an empty apartment. You get the keys (the IP and SSH access), and then you furnish it (install
  Python, nginx, Docker) and maintain it (updates, security) yourself.


 Droplet type                               CPU                                  Good for

 Basic (Regular or Premium                  Shared vCPU                          Websites, student projects, dev/test, small Django
 Intel/AMD)                                                                      apps

 General Purpose                            Dedicated (≈4 GB RAM per             Production web apps and APIs
                                            vCPU)

 CPU-Optimized                              Dedicated (≈2 GB per vCPU)           CPU-heavy work: CI builds, video encoding, batch
                                                                                 jobs

 Memory-Optimized                           Dedicated (≈8 GB per vCPU)           Caches, in-memory databases, big data sets

 Storage-Optimized                          Dedicated + large NVMe               Large databases, search indexes

 GPU Droplets                               NVIDIA GPUs                          AI/ML training and inference



▸ Creating a droplet: every choice, in order

 1        Sign up and open a project. Create a DigitalOcean account (a payment method is needed), then
          Create → Droplets.

 2        Choose a region (data centre). Pick the one closest to your users, e.g. BLR1 Bangalore, or London,
          Frankfurt, Singapore, New York. The droplet joins that region's default VPC (private network), so
          droplets in the same VPC can talk privately.

 3        Choose an image. OS: Ubuntu (e.g. 24.04 LTS), Debian, Fedora, Rocky/AlmaLinux. Marketplace: one-
          click images with software pre-installed (e.g. Docker, WordPress). Snapshots/backups: clone an earlier
          droplet. Custom images: upload your own.

 4        Choose a size (plan). The droplet type (above), then CPU, RAM, SSD and monthly data transfer. A
          small Django app runs on a 1–2 GB Basic droplet. You can resize later.

 5        Add storage (optional). Attach a Volume (block storage) if you need more disk than the plan gives.

--- PDF page 221 ---
6        Backups (optional, paid). Automatic weekly or daily backups (roughly 20% / 30% extra on the droplet
          price). Snapshots can be taken manually at any time.

 7        Authentication. SSH key (recommended: paste your public key) or a root password (simpler but
          weaker).

 8        Advanced options. Enable monitoring (free metrics agent for CPU/RAM/disk graphs and alerts), IPv6,
          and user data (a cloud-init script that runs on first boot, e.g. to install Docker).

 9        Finalize. Quantity, hostname (e.g. notes-app-prod ), tags and project.

 10       Create Droplet. After about a minute it shows a public IPv4 address. Copy it and connect:
            ssh root@<droplet-ip> .



▸ SSH key or password?

                        SSH key                                                                             Password

 How it works           A key pair: the public key goes on the droplet, the private key stays on your       The root password is typed at
                        laptop. Login proves you hold the private key                                       login

 Security               Very strong; cannot be guessed by brute force                                       Can be guessed or leaked; bots
                                                                                                            try constantly

 Convenience            No typing once set up                                                               Must remember and type it

 Recommendation         Use this (course: "secure login, no passwords")                                     Only for quick experiments


            your laptop


  ssh-keygen -t ed25519 -C "you@example.com"                    # creates ~/.ssh/id_ed25519 (private) +
  id_ed25519.pub (public)
  cat ~/.ssh/id_ed25519.pub                                     # paste THIS (public) into DigitalOcean
  ssh root@<droplet-ip>                                           # log in once the droplet is ready


Never share the private key or the root password (LEC 8 speaker notes).


▸ Pricing in one paragraph
Your notes say droplets are billed "hourly or monthly". Since January 2026 DigitalOcean bills droplets per sec‐
ond (60-second minimum), capped at the plan's monthly price, so you never pay more than the listed monthly
rate. The smallest Basic droplet starts at about $4/month, and 1–2 GB plans cost roughly $6–12/month.
Backups, snapshots, volumes and extra bandwidth cost extra. A powered-off droplet is still billed: you must
destroy it to stop charges. (Prices change; quote them as approximate.)

DigitalOcean vs AWS in one line: a droplet ≈ an EC2 instance and Spaces ≈ S3. DigitalOcean offers a focused
set of services with a gentle learning curve and flat monthly caps, which suits students, startups and small apps.
AWS offers 200+ services with granular pricing, which suits enterprises and very large or complex systems (the
full mapping table is in 3.16).

--- PDF page 222 ---
PYQ       Final 2024-25 · Q1(b)     Re-Exam 2023-24 · Q1(d)                                                                5 M each


  2024-25: What are Digital Ocean's Droplets.
  2023-24: What is Digital Ocean? Write a note on Droplets

   ✓   MODEL ANSWER: WRITE THIS

  DigitalOcean is a cloud infrastructure provider that offers simple, developer-friendly and affordable cloud
  services: virtual servers (Droplets), Spaces object storage, Managed Databases, App Platform (PaaS),
  Kubernetes, load balancers and firewalls. It is a paid service, billed by usage.

  Droplets are DigitalOcean's virtual private servers (VPS): Linux-based virtual machines running on DO's
  hardware that you rent and control like your own computer. A droplet is IaaS: DO manages the physical
  servers and network, and you manage the OS, software and data. It is like renting an empty apartment: you
  get the keys and set it up yourself.

  Key features:

       Choice of image: Ubuntu, Debian, Fedora, or one-click Marketplace apps (Docker, WordPress).
       Flexible sizes: CPU, RAM and SSD plans from Basic (shared CPU) to dedicated-CPU, memory- and
       storage-optimized; resizable later.
       Regions worldwide (e.g. Bangalore, London, New York) for low latency.
       Secure login with SSH keys (or a password), a public IP and full root access.
       Extras: backups and snapshots, attachable volumes, cloud firewalls, VPC private networking, free mon‐
       itoring, an API/CLI ( doctl ).
       Billing by usage (per second since 2026, capped monthly), from about $4/month.

  Creating one: sign up → Create → Droplets → choose region, OS image and plan → add SSH key →
  (backups/monitoring, hostname) → Create → copy the public IP → ssh root@<ip> .

  Uses: hosting websites and Django/Node APIs, running a Docker Compose stack, dev/test servers, learn‐
  ing Linux. Example: our notes app is deployed by SSH-ing into an Ubuntu droplet, installing Docker and
  running docker compose up -d --build .

  🎯 Marking scheme guess: 1 M what DigitalOcean is · 1.5 M droplet definition (VPS, IaaS, analogy) · 1.5 M features/choices (OS, size, re‐
  gion, SSH) · 1 M creation steps / uses




    3.18 Deploying the stack on a droplet
📚 Sources: Unit 3 Notes §9        LEC 8 slide 22   One-Shot Revision (Unit 5 · Compose)     Complete Revision deck slides 43–44


Deployment is packaging an application and running it, with everything it depends on, on a server that other
people can reach. A real app is never one process. It is a web server, the application code, a relational database,
perhaps a document database and a file store, all started in the right order and able to find each other. The
Docker details (images, layers, the Dockerfile and Compose syntax) are taught in the Unit 5 chapter. Here we
focus on what you do on the droplet and why.

--- PDF page 223 ---
▸ Two ways to deploy on a droplet

A · BY HAND (LEC 8 SLIDE 22)

           on the droplet


  ssh root@<droplet-ip>
  apt update && apt install -y python3-pip python3-venv nginx git
  git clone <repo> app && cd app
  python3 -m venv venv && source venv/bin/activate
  pip install -r requirements.txt
  gunicorn notes.wsgi --bind 0.0.0.0:8000
  # then: nginx proxy → :8000, PostgreSQL installed and configured by hand,
  #          a systemd service to keep gunicorn running


Every piece (Python, nginx, PostgreSQL) is installed and configured by hand on the server, and must be kept in sync with your laptop.


B · WITH DOCKER COMPOSE (UNIT 3 NOTES §9.6): THE COURSE'S WAY

           on the droplet


  ssh root@<droplet-ip>
  curl -fsSL https://get.docker.com | sh
  git clone <your-repo-url> app && cd app
  # edit compose.yaml / .env: change the passwords and set
  #     S3_PUBLIC_ENDPOINT: http://<droplet-ip>:9000
  docker compose up -d --build


"With Compose, the file is the server setup." An identical stack runs on the laptop and on the server. In the droplet's firewall allow SSH
(22), 8080 (site) and 9000 (downloads), then open http://<droplet-ip>:8080 .


  ⚠️ THE SLIDE'S PIP LINE FAILS ON NEW UBUNTU
  On Ubuntu 23.04 and later, pip install into the system Python stops with "error: externally-managed-
  environment". Create a virtual environment first ( python3 -m venv venv , as shown above) or use Docker.
  Also, gunicorn notes.wsgi alone listens only on 127.0.0.1:8000 , so add --bind 0.0.0.0:8000 or
  put nginx in front.



▸ Four Compose ideas that explain most deployment bugs

 Idea                       Meaning                                               Consequence

 Service names are          Containers reach each other by service name           Inside a container localhost = itself, so a DB host
 addresses                  ( db , web , mongo )                                  of localhost fails. Use HOST=db

 Started is not ready        depends_on + condition: ser‐                         Django doesn't crash trying to connect to a DB that is
                            vice_healthy waits for the healthcheck                still booting

 Volumes keep data          A container's own filesystem dies with it; a named    Data survives restarts, rebuilds and down
                            volume lives outside

--- PDF page 224 ---
Idea                   Meaning                                          Consequence

 Publish only what      Only nginx (and the storage download port) get   Databases are unreachable from the internet
 must be public          ports:


            compose.yaml: the deployment-relevant lines (full file in Unit 3 Notes §9.4)


  services:
     db:
        image: postgres:16
        environment:
           POSTGRES_PASSWORD: ${PG_PASS}                   # read from .env, never committed
        volumes:
           - pgdata:/var/lib/postgresql/data
        healthcheck: { test: ["CMD-SHELL", "pg_isready -U appuser -d appdb"], interval: 5s, retries:
  12 }
        restart: unless-stopped                            # comes back after a crash or reboot
        # no ports: only the app can reach it
     web:
        build: .                                           # image from the Dockerfile (gunicorn)
        environment:
           DATABASE_URL: postgresql://appuser:${PG_PASS}@db:5432/appdb                # host = service name
           S3_ENDPOINT: http://storage:9000                                           # app → storage (internal)
           S3_PUBLIC_ENDPOINT: http://<droplet-ip>:9000                             # links signed for browsers
        depends_on:
           db: { condition: service_healthy }
        restart: unless-stopped
     nginx:
        image: nginx:1.27-alpine
        ports: ["8080:80"]                                 # the single public entrance
        depends_on: [web]
  volumes:
     pgdata:



            .env (next to compose.yaml, listed in .gitignore)


  PG_PASS=a-long-random-password
  DJANGO_SECRET_KEY=another-long-random-value
  DJANGO_DEBUG=False




▸ Running it, and what survives

            day-to-day commands on the droplet


  docker compose up -d --build                 # build and start every service in the background
  docker compose ps                            # are the services up and healthy?
  docker compose logs -f web                   # follow one service's logs

--- PDF page 225 ---
git pull && docker compose up -d --build                          # redeploy a new version
  docker compose exec -T db pg_dump -U appuser appdb > backup.sql                               # back up the database
  docker compose down                                  # stop + remove containers, KEEP volumes
  docker compose down -v                               # also DELETE volumes (all data)



 Command                                 What happens               Why

  down , then up -d                      All data is still there    Named volumes were kept

  down -v , then up -d                   Everything starts emp‐     Volumes deleted: Postgres re-runs the ./sql init files, MongoDB is
                                         ty again                   empty, the bucket must be recreated

 Droplet reboot                          Stack comes back by        Docker starts on boot and restart: unless-stopped restarts
                                         itself                     the containers

 Changed a file in ./sql , noth‐         Init scripts did not run   They run only on an empty volume: apply via psql, or down -v
 ing happened                                                       (deletes data)


Going to production (beyond the lab): point a domain's DNS A record at the droplet IP, serve on ports 80/443 with a free Let's Encrypt
HTTPS certificate, close 8080/9000 behind nginx, set DEBUG=False and ALLOWED_HOSTS , and enable droplet backups.


   ✏️ COMPLETE THE COMMANDS: FROM LAPTOP TO LI VE S ITE
    1. Make an SSH key pair: ssh-keygen -t
    2. Log in to the droplet:                         root@203.0.113.10

    3. Install Docker: curl -fsSL https://get.docker.com |
    4. Fetch the code: git                           https://github.com/user/repo.git app

    5. Build and start in the background: docker compose up
    6. Stop but keep the database: docker compose                                    ; stop and wipe it:
        docker compose down

    7. Inside a container the DB host must be the                               , not localhost .

   🔓 Answer key: 1) ed25519 · 2) ssh · 3) sh · 4) clone · 5) -d --build · 6) down; -v · 7) service name (db)


    3.19 Putting it together: the full architecture
📚 Sources: Unit 3 Notes §10        LEC 8 slide 23      Complete Revision deck slide 44

--- PDF page 226 ---
Users reach one door, nginx, and only the app talks to the data stores

                                     Docker Compose on one server (a DigitalOcean droplet)

                                                                                                                                PostgreSQL
                                                                                                                            records · volume pgdata




          Browser            http              nginx               /api/           web: Django                                   MongoDB
                                            single entrance                     gunicorn · ORM · DRF
       React UI · the user                                                                                                 activity logs · mongodata
                                               port 8080                              port 8000



                                                                                                                                 S3 storage
                                                                                                                          files · private bucket · :9000




                                                browser downloads a file directly with a presigned link (port 9000)




      Redrawn from Unit 3 Notes §10. Databases publish no ports; the dashed line is the only direct path from the browser to a data store.


 Request step                                           Part involved                                     Concept (section)

 Browser asks for a page or an API call                 nginx                                             Single entrance, reverse proxy (3.18)

 Application code runs                                  Django container (gunicorn)                       Dockerfile, service names (3.18 · Unit 5)

 A record is read or changed                            PostgreSQL                                        Tables, joins, transactions (3.2–3.9)

 An event is logged                                     MongoDB                                           Flexible documents (3.10)

 A file is stored or fetched                            S3-compatible storage                             Key in the DB, file in the bucket (3.14)

 Everything is started together                         Docker Compose on a droplet                       IaaS + deployment (3.15–3.18)


LEC 8 slide 23 shows the same picture with AWS S3 as the file store and HTTPS at the front: User → Nginx →
Gunicorn + Django (REST API, ML model) → PostgreSQL (users, notes), MongoDB (activity, logs), AWS S3
(files), all on an Ubuntu droplet. If an exam asks you to "draw the architecture of a deployed full-stack app",
draw this and label each arrow.




    3.20 Common mistakes and fixes
📚 Sources: Unit 3 Notes §11         LEC 8 slide 24      One-Shot Revision


 Mistake                                   Risk                                        Fix

 Plain-text passwords                      Leaked accounts                             Hash them, as Django's auth does ( create_user() )

 A public S3 bucket                        Anyone can read the files                   Private bucket, IAM rules and presigned links

 Keys hard-coded in code                   Leaks through GitHub                        Environment variables and a .env kept out of Git

 Database port open to everyone            Direct attacks                              Don't publish it, or firewall it to the app only

 No backups                                Permanent data loss                         Snapshots and pg_dump

  DEBUG = True in production               Exposes secrets and settings                 DEBUG = False

 SQL built with f-strings                  SQL injection                               Pass values as %s parameters

--- PDF page 227 ---
Deployment symptom                                        Usual cause

 The app cannot connect to a service                       Read that service's logs: docker compose logs <service>

 Connection refused to the database                        Host is localhost inside a container. Use the service name

 A file download link fails                                The public storage address is not reachable from the browser

 "Port is already allocated"                               Another program uses it. Change the left number in ports

 Changed ./sql and nothing happened                        Init scripts run only on an empty volume



  ⚠️ SQL SLIPS THAT LOSE MARKS IN THE SCRIPT QUESTIONS
       UPDATE/DELETE without WHERE · comparing with = NULL instead of IS NULL · double quotes
       around string values in PostgreSQL.
       A hyphen in a column name ( Job-Title ) left unquoted · salary as FLOAT · phone as INT.
       LIMIT before ORDER BY, or an aggregate in WHERE (use HAVING) · a SELECT alias used in WHERE.
       Forgetting the semicolons, or the column list in INSERT.


  ✍️ HOW TO ANSWER "SECURITY / BEST PRACTICES FOR DEPLOYMENT"
  Group the fixes by layer, exactly as your notes advise: secrets → environment variables; access → private
  bucket and closed ports; recovery → backups. One idea per layer.




     3.21 Likely questions for 2026
📚 Sources: All three past papers      Unit 3 Notes    LEC 8 (Databases & Deployment)


 #     Predicted question                                                      Marks     Answer pointer

 1      HIGH    Compare SQL and NoSQL / explain ACID vs BASE / ver‐            6–10      3.12 model answer; ACID–BASE table and CAP in
       tical vs horizontal scaling                                                       3.11

 2      HIGH    Write SQL to create a table, insert 5 rows, add a column,      10        3.4: same 5-step template, PK for "nth record",
       update one row, delete one row (new table/fields)                                 DECIMAL for money, VARCHAR for phone, show
                                                                                         outputs

 3      HIGH    Query: top-N / average / department-wise counts with           4–5       3.5–3.6. e.g. SELECT dept_id,
       GROUP BY + HAVING / a join                                                        AVG(marks) FROM students GROUP BY
                                                                                         dept_id HAVING AVG(marks) > 70;

 4      HIGH    What is AWS? Explain any 5 services (or: EC2 vs S3 vs          10        3.16 model answer: definition + regions/AZ + E-S-
       RDS)                                                                              R-L-I

 5      MEDIUM       DigitalOcean droplets: what, steps to create, deploy      5–10      3.17 steps (region, image, size, SSH key, backups,
       a Django app                                                                      monitoring, hostname) + 3.18 commands

 6      MEDIUM       Normalization 1NF–3NF with an example; when to            4–6       3.7 worked example; "the key, the whole key,
       denormalize                                                                       nothing but the key"

 7      MEDIUM       Transactions: ACID,                                       5–8       3.9: bank transfer, state diagram, savepoint code
       BEGIN/COMMIT/ROLLBACK/SAVEPOINT, states of a transaction

--- PDF page 228 ---
#      Predicted question                                                    Marks      Answer pointer

 8       MEDIUM     Django ORM: model → table, ORM vs raw SQL,                4–6        3.13 mapping table + 4-point model answer
        Django with MongoDB

 9       LOW    IaaS vs PaaS vs SaaS with examples; why S3 for files          4–5        3.15 table + pizza; 3.14 "file in S3, key in DB"
        (buckets, keys, presigned URLs)

 10      LOW    MongoDB CRUD in mongosh / four NoSQL types / DDL-             4–5        3.10 code; 3.3 table
        DML-DQL-DCL-TCL




      3.22 Last-minute recap
📚 Sources: Unit 3 Notes §12       LEC 8 slide 25     One-Shot Revision     Complete Revision deck


 Topic              Must-remember facts

 Why a DB           Persistence, integrity, concurrency, querying, security/recovery (P-I-C-Q-S)

 Keys               PK = unique + not null, one per table · FK = points at another PK, enforced (referential integrity) · NULL = no value

 Command            DDL CREATE/ALTER/DROP/TRUNCATE · DML INSERT/UPDATE/DELETE · DQL SELECT · DCL GRANT/REVOKE ·
 groups             TCL BEGIN/COMMIT/ROLLBACK/SAVEPOINT

 Remove             DELETE = chosen rows · TRUNCATE = all rows, table stays · DROP = table gone

 Clause run         FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT (aliases not usable in WHERE)
 order

 Joins              INNER matches · LEFT/RIGHT keep one side · FULL keeps all · CROSS = A×B · SELF = two aliases

 Normal forms       1NF atomic · 2NF no partial dependency · 3NF no transitive dependency · denormalize for read speed

 ACID               Atomicity, Consistency, Isolation, Durability · states Active → Partially committed → Committed / Failed → Aborted

 BASE · CAP         Basically Available, Soft state, Eventual consistency · in a partition choose C or A (CP vs AP)

 Scaling            Vertical = bigger server (SQL) · horizontal = more servers (NoSQL) · replication = copies · sharding = split by key

 MongoDB            Collection/document/field, _id · insertOne, find, updateOne + $set, deleteOne · document, key-value, column,
                    graph

 Django +           ORM is SQL-only · djongo (dead), MongoEngine (own ODM), django-mongodb-backend (official, GA 2025), pymon‐
 Mongo              go beside ORM

 S3                 Bucket · object · key · file in S3, key in DB · private + IAM + presigned URL (expiring) · boto3

 Cloud models       On-prem → IaaS (droplet, EC2) → PaaS (Heroku) → SaaS (Gmail): more managed = less control

 AWS five           EC2 compute · S3 storage · RDS SQL · Lambda serverless · IAM security (+ DynamoDB, CloudFront, Route 53, VPC,
                    Beanstalk, CloudWatch, SageMaker)

 Droplet            DO's VPS (IaaS) · choose region, image/OS, size, SSH key or password, backups, monitoring, hostname · per-sec‐
                    ond billing, from ~$4/mo

 Deploy                 ssh root@ip → install Docker → git clone → docker compose up -d --build · service names
                    not localhost · volumes keep data · down -v wipes it


            skeletons to reproduce from memory

--- PDF page 229 ---
CREATE TABLE Emp (Emp_ID INT PRIMARY KEY, F_Name VARCHAR(50) NOT NULL, Salary DECIMAL(10,2));
  INSERT INTO Emp (Emp_ID, F_Name, Salary) VALUES (1,'Asha',65000.00), (2,'Ravi',55000.00);
  ALTER TABLE Emp ADD COLUMN Contact_No VARCHAR(15);
  UPDATE Emp SET Salary = 48000.00 WHERE Emp_ID = 2;
  DELETE FROM Emp WHERE Emp_ID = 1;
  SELECT name, marks FROM students WHERE marks > 75 ORDER BY marks DESC LIMIT 5;
  SELECT AVG(marks) FROM students WHERE marks > 75;
  SELECT dept_id, COUNT(*) FROM students GROUP BY dept_id HAVING COUNT(*) > 1;
  BEGIN; UPDATE ...; SAVEPOINT s; UPDATE ...; ROLLBACK TO s; COMMIT;



           mongosh · boto3 · droplet


  db.students.find({ marks: { $gt: 75 } }).sort({ marks: -1 }).limit(5)         # mongosh
  db.students.updateOne({ name: "Asha" }, { $set: { marks: 85 } })                # mongosh
  s3.upload_fileobj(f, "app-media", "profile/asha.jpg")                           # boto3
  s3.generate_presigned_url("get_object", Params={...}, ExpiresIn=300)            # boto3
  ssh root@<ip> ; curl -fsSL https://get.docker.com | sh ; docker compose up -d --build