Skip to lesson content
Web Technologies › Level 26
LEVEL 26 · DATABASES + SQL

Databases and SQL for Web Applications

Design related data and explain every row in a grouped SQL report.

☕ Java web🔗 Relationships📊 SQL reports🧪 Lab + MCQs
01

Learning Objectives

Design

Separate learners, courses and enrollments.

Integrity

Choose keys and constraints deliberately.

Query

Compare inner/left joins and filter placement.

Report

Count matches, group, sort and limit results.

02

Relational Data Behind a Web Application

Application data flow
Frontend

Requests an allowed operation.

Backend

Validates and authorizes.

Database

Stores facts and enforces rules.

Accepted model

Returns deliberate presentation data.

03

Entities and Many-to-Many Relationships

Enrollment relationship
Learners

learner_id identifies a learner.

Enrollments

learner_id + course_id identify the pair.

Courses

course_id identifies a course.

04

Primary Keys, Foreign Keys and Pair Uniqueness

CREATE TABLE learners (
    learner_id INTEGER PRIMARY KEY,
    name TEXT NOT NULL
);
CREATE TABLE courses (
    course_id INTEGER PRIMARY KEY,
    title TEXT NOT NULL
);
CREATE TABLE enrollments (
    learner_id INTEGER NOT NULL REFERENCES learners(learner_id),
    course_id INTEGER NOT NULL REFERENCES courses(course_id),
    status TEXT NOT NULL CHECK (status IN ('active', 'completed')),
    grade INTEGER CHECK (grade BETWEEN 0 AND 100),
    PRIMARY KEY (learner_id, course_id)
);
05

Types, Nullability and Constraints

Identity

Keys prevent duplicate identity/pairs.

Reference

Foreign keys protect relationships.

Value rule

A CHECK constrains accepted values.

Missing data

Nullable grade means not yet known.

06

Normalization and Update Anomalies

Avoid repeated profile/course data in every enrollment:
learner_name, learner_email, course_title, status, grade

Prefer related facts:
learners(learner_id, name)
courses(course_id, title)
enrollments(learner_id, course_id, status, grade)
07

SELECT, WHERE and Deterministic Ordering

SELECT course_id, title
FROM courses
ORDER BY course_id
LIMIT ?;

-- Bind a validated limit; do not concatenate arbitrary SQL.
08

INSERT, UPDATE and DELETE with Deliberate Scope

INSERT INTO enrollments (learner_id, course_id, status, grade)
VALUES (?, ?, ?, ?);

UPDATE enrollments
SET status = ?, grade = ?
WHERE learner_id = ? AND course_id = ?;

DELETE FROM enrollments
WHERE learner_id = ? AND course_id = ?;
09

INNER JOIN and LEFT JOIN

SELECT c.course_id, c.title, e.learner_id, e.status
FROM courses AS c
LEFT JOIN enrollments AS e ON e.course_id = c.course_id
ORDER BY c.course_id, e.learner_id;
Normal joined rows
HTML

Two matching enrollments.

JSP

One matching enrollment.

SQL

One null-extended row in a left join.

10

ON Filters and WHERE Filters Differ

The lab’s all-status option omits the status predicate altogether, so switching its ON/WHERE selector has no effect in that case.

-- Preserve courses with zero completed enrollments:
LEFT JOIN enrollments e
  ON e.course_id = c.course_id AND e.status = ?

-- Filter joined rows; unmatched courses do not pass:
LEFT JOIN enrollments e ON e.course_id = c.course_id
WHERE e.status = ?
11

NULL, COUNT and AVG

SELECT c.course_id, c.title,
       COUNT(e.learner_id) AS enrollment_count,
       AVG(e.grade) AS average_grade
FROM courses c
LEFT JOIN enrollments e ON e.course_id = c.course_id
GROUP BY c.course_id, c.title
ORDER BY c.course_id;
12

GROUP BY, HAVING and Report Stages

GROUP BY c.course_id, c.title
HAVING COUNT(e.learner_id) >= ?
ORDER BY c.course_id
LIMIT ?;
Logical report stages
Join

Match and null-extend as required.

WHERE

Filter joined rows.

Group/HAVING

Compute and retain report groups.

Order/limit

Return the final bounded report.

13

Indexes and Query Plans

CREATE INDEX enrollments_by_course
ON enrollments(course_id);

EXPLAIN QUERY PLAN
SELECT learner_id, status
FROM enrollments
WHERE course_id = 101;
14

Transactions, Migrations and Backups

Atomic work

Resolve related changes deliberately.

Migration

Version and validate schema changes.

Backup

Protect database state separately.

Restore

Test recovery, not just backup creation.

15

Application Boundaries and Verification

Zero match

Left joins preserve a null-extended course.

Counting

Count the relationship key for enrollment totals.

No grade

Keep a NULL average distinct from zero.

Integration

Check actual deployment and workload separately.

Next, Level 27 develops Web APIs and REST: the application contract between the frontend and backend data operations.

16

Premium Visualizer — A Relational Course Report

Follow related tables through a left join, aggregation, group filtering and bounded output. This approved five-stage player explains a fixed course report; it is not a database execution plan.

SQL COURSE REPORT TRACE
Step 1 of 5
STEP 01

Identify related facts

Separate learners, courses and their enrollment pairs.

learners + courses + enrollments

What is happening?

Keys and references preserve the intended relationships.

17

Premium Interactive — Joins, Filters and Course Reports

Idle. Local model; no database is connected.

Local fixture tables

Prepared SQL and separate parameters

No accepted query yet.

Joined rows after ON and WHERE · before grouping

No joined rows yet.

Report stage trace

No trace yet.

Accepted report rows

No accepted report.

Simulated response

No response yet.

Safe text preview

No report yet.
18

Debugging — Ask Which Rows Survive

Join

Check the relationship predicate and match multiplicity.

Filter

Distinguish ON matching from WHERE removal.

Count

Avoid counting a null-extended row as enrollment.

Grade

Do not convert absent grades into zeros.

19

Interview Questions — Flip to Explain

QUESTION

Why use an enrollment junction table?

Click or press Enter to explain
ANSWER

It represents the many-to-many learner/course relationship and stores facts about that pair.

QUESTION

What does the composite enrollment key protect?

Click or press Enter to explain
ANSWER

It prevents duplicate learner/course pairs in this schema.

QUESTION

Does a LEFT JOIN always keep empty courses after WHERE?

Click or press Enter to explain
ANSWER

No. A right-table WHERE predicate can remove their null-extended rows.

QUESTION

Why count e.learner_id rather than star for enrollment totals?

Click or press Enter to explain
ANSWER

COUNT of the non-null enrollment key excludes the unmatched placeholder; COUNT(*) counts that joined row.

QUESTION

How does AVG treat missing grades here?

Click or press Enter to explain
ANSWER

It ignores NULL grades; a group with no non-null grade has a NULL average.

QUESTION

How do WHERE and HAVING differ?

Click or press Enter to explain
ANSWER

WHERE filters input rows; HAVING filters aggregated groups.

QUESTION

Does an index guarantee faster queries?

Click or press Enter to explain
ANSWER

No. Use the actual workload and query plan; indexes also cost storage and mutation work.

QUESTION

Do local SQLite checks verify the deployed backend?

Click or press Enter to explain
ANSWER

No. They verify the chosen local examples; deployment, driver, authorization and concurrency need separate checks.

20

MCQ Practice — Explain SQL Report Decisions

PRACTICE

1. Which table represents learner/course membership?

PRACTICE

2. What prevents a duplicate learner/course pair in the schema?

PRACTICE

3. Which join preserves a course with no enrollment before later filters?

PRACTICE

4. Where can a right-table status filter remove those empty courses?

PRACTICE

5. Which count reports actual matched enrollments?

PRACTICE

6. What is the average of grades 88, 72 and NULL?

PRACTICE

7. How is missing grade tested in SQL?

PRACTICE

8. Which clause filters report groups by their count?

PRACTICE

9. Which clause establishes the intended result order?

PRACTICE

10. What does the lab do with an orphan fixture?

PRACTICE

11. What must the SQLite constraint check enable?

PRACTICE

12. Do prepared parameters replace authorization?

21

Extra Practice — Predict the Exact Report

Default left report

All/on/enrollment count/min0/limit3: HTML count2 average80, JSP count1 NULL, SQL count0 NULL.

Inner report

Change to inner: HTML and JSP only; SQL has no matching enrollment.

Completed in ON

Left/completed/on: HTML2, JSP0, SQL0. All courses remain.

Completed in WHERE

Left/completed/where: HTML2 only. The zero-match courses disappear.

Joined-row trap

Left/completed/on/count rows/min1: JSP and SQL each show count1, despite zero enrollments.

Filter before limit

Left/active/on/enrollment count/min1/limit1: JSP is the single retained group.

Rejected fixture

Choose orphan: 500 and no old report. Empty: 200 and a completed zero-row message.

Invalid parameters

Try minimum 00, limit 03, missing/repeated/extra shape: 400 before fixture reporting.

22

Quick Revision

Entities: One clear fact per row.
Relationships: Junction table for many-to-many.
Keys: Identity and pair uniqueness.
Constraints: Preserve references and accepted values.
Filters: ON and WHERE have different left-join effects.
Counts: Count matches rather than placeholders.
NULL: Missing grade is not zero.
Groups: HAVING filters computed groups.
Indexes: Verify actual plans and workloads.
Verification: Separate local SQL from deployed integration.
23

Glossary — Flip to Learn

TERM

Relational table

Click to see meaning
DEFINITION

Relational table

A set of rows organized into named columns and rules.

TERM

Primary key

Click to see meaning
DEFINITION

Primary key

A key identifying a row uniquely.

TERM

Foreign key

Click to see meaning
DEFINITION

Foreign key

A relationship constraint referencing a parent key.

TERM

Junction table

Click to see meaning
DEFINITION

Junction table

A table representing pairs in a many-to-many relationship.

TERM

Normalization

Click to see meaning
DEFINITION

Normalization

Organizing facts around meaningful dependencies to reduce anomalies.

TERM

LEFT JOIN

Click to see meaning
DEFINITION

LEFT JOIN

A join preserving unmatched left rows with null right-side values.

TERM

NULL

Click to see meaning
DEFINITION

NULL

A marker for missing or unknown data.

TERM

Aggregate

Click to see meaning
DEFINITION

Aggregate

A calculation over rows, such as COUNT or AVG.

TERM

HAVING

Click to see meaning
DEFINITION

HAVING

A condition applied to aggregated groups.

TERM

Migration

Click to see meaning
DEFINITION

Migration

A versioned change to a database schema or related data.

24

Final Challenge — Design an Enrollment Report

Success criterion: predict the exact course rows and counts before executing the query. Next: Level 27 — Web APIs and REST.

25

Level 26 Complete?

Explain the schema relationships and constraints, reproduce the join/filter/count differences, and distinguish NULL averages from zero. Identify the production checks that local SQLite and browser-model tests do not establish. Completion is a local study marker.