Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Database Management Systems (DBMS)  Module 1 – Foundations: what a DBMS does and how it works

What a DBMS does and why files are not enough

What a database management system (DBMS) adds to plain files: integrity, concurrency, recovery and security, with a lost update and a crash reproduced.

  • Beginner
  • 35 minutes
  • Examples run with sql.js 1.14.2 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 35 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Explain the problems a DBMS solves that ad-hoc files cannot, from integrity and concurrency to recovery and security
  • Describe the three-schema architecture and the difference between logical and physical data independence
  • Classify statements as DDL, DML, DCL or TCL and name the people who use a database system
  • Compare relational, document, key-value, wide-column, graph and vector data models at a high level
  • Query a database's catalog to read its schema as data
What you’ll learn

What you will learn

  • Explain the problems a DBMS solves that ad-hoc files cannot, from integrity and concurrency to recovery and security
  • Describe the three-schema architecture and the difference between logical and physical data independence
  • Classify statements as DDL, DML, DCL or TCL and name the people who use a database system
  • Compare relational, document, key-value, wide-column, graph and vector data models at a high level
  • Query a database's catalog to read its schema as data
On this page

Two writers each add 1, yet their shared counter ends at 1; a crash leaves just 8,000 of 16,000 file characters. A database management system: Software that manages stored data and mediates requests to read or change it while providing integrity, concurrency, recovery and access services. puts integrity checks, transaction coordination, recovery and access control between those writers and stored data.

Moving a counter into SQLite does not repair a split read-and-write request: the database must perform the update safely. Compare all three counter outcomes and the recovered marks, then use catalog queries, indexes and views to distinguish the data’s description from its storage.

A shared database tackles five file failures

A database management system (DBMS) is the software that keeps a collection of data and handles every request to read or change it. Programs do not open the data files themselves: they send requests, usually in SQL, and the DBMS decides how to carry each one out. Because every read and write passes through it, the DBMS can do four jobs that plain files leave to every program that touches them. It checks the rules the data must obey (integrity). It stops two writers from undoing each other’s work (concurrency control). It brings the data back to a consistent state after a crash (recovery). And it decides who may see or change what (security). It also keeps a description of the data, the schema, so that a program can ask a question without knowing how the data is laid out on disk.

This lesson reproduces two of the failures that plain files suffer, shows what a DBMS does instead, and then covers the vocabulary every database course and interview uses: schemas and the catalog, the three-schema architecture and data independence, the classes of SQL statements, the people who work with a database, and the main data models.

Picture a college that keeps its records in files: a spreadsheet of students in the office, a CSV file of hostel rooms on the warden’s computer, and a JSON file of marks that a small web app reads and rewrites. That works while one person uses each file. Once the data is shared, the same five problems appear again and again:

  • Redundant, inconsistent copies. A student’s phone number sits in the office spreadsheet and in the hostel file. A change made in one copy never reaches the other, and nobody can tell which copy is right.
  • Rules buried in code. The web app refuses a mark above 100, but the script that imports marks from the exam portal checks nothing, so a mark of 140 gets in through the script.
  • lost update: A change that is overwritten when another writer saves a value computed from an older read of the same data. Two people change the same file at about the same time. Each starts from the old version, and whoever saves last silently undoes the other’s change.
  • Half-written files. A program dies, or the power fails, while it is rewriting a file, and leaves something that is neither the old version nor the new one.
  • All-or-nothing security. The operating system grants access to a whole file. It cannot let the warden read room numbers but not marks when both live in the same file.

A DBMS answers each problem with a service of its own:

Problem with files What the DBMS provides How, in one line
Redundant, inconsistent copies One shared database Each fact is stored once, and every program reads that one copy
Rules buried in code Integrity constraints The schema states the rules and every write is checked against them
Lost updates Concurrency control Transactions keep simultaneous writers from overwriting each other
Half-written files Recovery A journal or log lets the DBMS undo or finish interrupted changes
All-or-nothing security Access control Privileges on tables, columns and views, granted to users and roles

The next four sections show four of these at work, with programs whose output you can check line by line.

Step through the five file failures and match each one to the service that addresses it:

Interactive · stage by stage Five file failures and the DBMS services Step through the college files and identify which service addresses each failure.
Five file failures and the DBMS services, step 5 of 5. Showing Shared files, DBMS services. In focus: DBMS services.Shared filesDBMS services

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Copies disagree. The office and hostel keep separate phone numbers. One shared source reduces the inconsistent copies that every reader otherwise has to reconcile.
  2. A rule is bypassed. The web app rejects marks above 100, but an import accepts 140. Integrity constraints check the write at the shared database boundary.
  3. One update vanishes. Two writers start from the old counter and save separate results. Concurrency control must coordinate the whole update, not just store the same data in a new file.
  4. A write is interrupted. A writer stops after part of the new file is saved. Recovery uses the journal or log to leave a complete state after the interruption.
  5. A role sees too much. Whole-file access exposes both rooms and marks. A client-server database can grant the warden only the room columns or a suitable view.

Checkpoint

Check: Five file failures

  1. Question 1 of 2 An importer accepts mark 140 although the web app refuses it. Which shared boundary should enforce the range?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A schema integrity constraint

    Place the rule where all writes are checked, rather than in only one writer.

  2. Question 2 of 2 The warden needs rooms but not marks. Which DBMS service addresses this requirement?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Access control

    The required service follows from who may see the fields, not from a crash or a lost update.

A write transaction counts both increments

The program below has two writers, A and B, and each adds 1 to a shared counter. Real writers run at the same time, so their steps can interleave in many orders. The program fixes one unlucky order, so that every run gives the same result: both writers read the counter before either writes it back.

Two writers, one counter Python · lost_update.py
"""Two writers each add 1 to a shared counter, with their steps interleaved in a fixed order."""
import json
import sqlite3

# 1. The counter in a JSON file: each writer reads the file, adds 1 and writes it back.
with open("counter.json", "w") as f:
    json.dump({"n": 0}, f)


def read_file():
    with open("counter.json") as f:
        return json.load(f)["n"]


def write_file(n):
    with open("counter.json", "w") as f:
        json.dump({"n": n}, f)


a = read_file()      # writer A reads 0
b = read_file()      # writer B reads 0, before A has written anything
write_file(a + 1)    # A writes 1
write_file(b + 1)    # B writes 1 as well: A's increment is gone
print("JSON file, read then write:     n =", read_file())

# 2. The same two steps against SQLite: a SELECT, then an UPDATE with the value Python computed.
setup = sqlite3.connect("counter.db", autocommit=True)
setup.execute("CREATE TABLE counter (n INTEGER NOT NULL)")
setup.execute("INSERT INTO counter VALUES (0)")
A = sqlite3.connect("counter.db", autocommit=True, timeout=0)
B = sqlite3.connect("counter.db", autocommit=True, timeout=0)
READ = "SELECT n FROM counter"
a = A.execute(READ).fetchone()[0]
b = B.execute(READ).fetchone()[0]
A.execute("UPDATE counter SET n = ?", (a + 1,))
B.execute("UPDATE counter SET n = ?", (b + 1,))
print("SQLite, read then write:        n =", setup.execute(READ).fetchone()[0])

# 3. The database does the arithmetic, inside a write transaction.
setup.execute("UPDATE counter SET n = 0")
A.execute("BEGIN IMMEDIATE")              # A starts a write transaction
A.execute("UPDATE counter SET n = n + 1")
try:
    B.execute("BEGIN IMMEDIATE")          # B asks to write while A's transaction is open
except sqlite3.OperationalError as e:
    print("B asks to write while A is busy:", e)
A.execute("COMMIT")
B.execute("BEGIN IMMEDIATE")              # now it is B's turn
B.execute("UPDATE counter SET n = n + 1")
B.execute("COMMIT")
print("SQLite, UPDATE ... n = n + 1:   n =", setup.execute(READ).fetchone()[0])

Output

JSON file, read then write:     n = 1
SQLite, read then write:        n = 1
B asks to write while A is busy: database is locked
SQLite, UPDATE ... n = n + 1:   n = 2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 lost_update.py

Read the three results in turn:

  1. The JSON file ends at 1, not 2. B computed its new value from a stale read, so A’s increment vanished. No error was raised; the data is simply wrong.
  2. SQLite ends at 1 as well. The program read the value with one statement, added 1 in Python and wrote the result with a second statement. Each statement was correct on its own; the bug lives in the gap between them. A DBMS gives you the tools against lost updates, but a program that reads, computes and writes in separate steps, outside a transaction, still loses them.
  3. UPDATE counter SET n = n + 1 ends at 2. The read and the write are now one statement that SQLite runs under its write lock, and A wraps it in a write transaction (BEGIN IMMEDIATE). While that transaction is open, B’s request to start writing is refused with “database is locked”. The program sets timeout=0 so that the refusal shows; by default Python’s sqlite3 module waits up to five seconds for the lock instead. Once A commits, B takes its turn, and both increments count.

SQLite allows any number of readers but only one writer at a time per database file, as its own documentation says. PostgreSQL and MySQL let many transactions write at once: PostgreSQL keeps them apart with row versions (multiversion concurrency control) and row-level locks, and MySQL’s InnoDB engine locks individual rows. The modules on transactions and concurrency control in this track show how.

Follow every read, write and transaction request in the three cases; identify when B must wait:

Interactive · stage by stage The three counter outcomes of the original program Follow both reads, both writes and the refused transaction; compare all three complete outcomes.
The three counter outcomes of the original program, step 8 of 8. Showing JSON counter, SQLite split update, SQLite transaction. In focus: SQLite transaction.JSON counterSQLite split updateSQLite transaction

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. Both JSON readers see 0. Writer A reads 0 and writer B also reads 0 before either saves. Each keeps its own value to which it will add 1.
  2. The last save wins. A writes 1 and B writes 1 from its stale read. The JSON counter ends at 1 although two increments were requested.
  3. Both SQL readers see 0. The two SQLite connections each SELECT 0 outside a shared read-modify-write transaction. Moving the counter into SQLite alone has not changed the interleaving.
  4. Two SQL writes leave 1. A and B each UPDATE the value their Python code computed. Both save 1, so this SQLite case loses the increment too.
  5. A requests the write lock. A begins an IMMEDIATE transaction and runs UPDATE counter SET n = n + 1. The database performs the arithmetic under its write transaction.
  6. B is refused while A writes. B requests BEGIN IMMEDIATE while A still owns the write transaction. With timeout 0, the program prints database is locked immediately.
  7. A commits its increment. A COMMIT releases its write transaction. The committed value is 1 and B can now start its own turn.
  8. B makes the counter 2. B begins its transaction, computes n + 1 in SQLite and commits. Both increments now count and the final value is 2.

Checkpoint

Check: Count both increments

  1. Question 1 of 2 What event lets B start its successful write transaction in the counter run?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A commits

    B is refused while A writes and can take its turn after A commits.

  2. Question 2 of 2 Both writers use the successful arithmetic UPDATE transaction. What final counter value follows?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 2

    A commits 1, then B computes and commits 2.

A journal recovers all 1000 marks

The second program raises every mark by 5 and dies halfway through, once with a JSON file and once with SQLite. Each update runs in a separate Python process that ends with os._exit(1), which stops a program the way a crash does: nothing is cleaned up, flushed or closed.

A crash in the middle of an update Python · crash_midway.py
"""A program dies halfway through an update: first with a plain file, then with SQLite."""
import hashlib
import json
import os
import sqlite3
import subprocess
import sys

STUDENTS = 1000
marks = {f"21CS{i:04}": 40 + i % 50 for i in range(STUDENTS)}


def die_after(code):
    """Runs `code` in a new Python process that is killed (os._exit) once the code has run."""
    subprocess.run([sys.executable, "-c", code + "\nimport os\nos._exit(1)"], check=False)


def fingerprint(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()


# 1. A plain file. Every mark goes up by 5, but the program dies while it rewrites the file.
with open("marks.json", "w") as f:
    json.dump(marks, f)
die_after("""
import json
marks = json.load(open("marks.json"))
text = json.dumps({roll: mark + 5 for roll, mark in marks.items()})
f = open("marks.json", "w")        # opening a file for writing empties it at once
f.write(text[: len(text) // 2])    # half of the new text is written...
f.flush()                          # ...and handed to the operating system
""")
text = open("marks.json").read()
full = len(json.dumps(marks))
print(f"file: {len(text):,} of {full:,} characters left, ending {text[-15:]!r}")
try:
    json.loads(text)
except json.JSONDecodeError as e:
    print("file: unreadable:", e.msg)

# 2. SQLite. The same update inside a transaction; the program dies before COMMIT.
db = sqlite3.connect("marks.db", autocommit=True)
db.execute("CREATE TABLE marks (roll TEXT PRIMARY KEY, mark INTEGER NOT NULL, remarks TEXT)")
rows = [(roll, mark, "-" * 300) for roll, mark in marks.items()]
db.executemany("INSERT INTO marks VALUES (?, ?, ?)", rows)
db.close()
before = fingerprint("marks.db")
die_after("""
import sqlite3
db = sqlite3.connect("marks.db", autocommit=True)
# Room for 10 pages in memory, far fewer than the update changes, so SQLite
# writes changed pages into the database file before COMMIT.
db.execute("PRAGMA cache_size = 10")
db.execute("PRAGMA cache_spill = ON")
db.execute("BEGIN")
db.execute("UPDATE marks SET mark = mark + 5")
""")
print("database file changed on disk before COMMIT:", fingerprint("marks.db") != before)
print("rollback journal next to it:", os.path.exists("marks.db-journal"))

db = sqlite3.connect("marks.db")         # the next program that opens the database
CHANGED = "SELECT count(*) FROM marks WHERE mark <> 40 + CAST(substr(roll, 5) AS INTEGER) % 50"
changed = db.execute(CHANGED).fetchone()[0]
print(f"after reopening: {changed} of {STUDENTS:,} marks changed")
db.close()
print("rollback journal still there:", os.path.exists("marks.db-journal"))
print("database file identical to before the update:", fingerprint("marks.db") == before)

Output

file: 8,000 of 16,000 characters left, ending '"21CS0499": 94,'
file: unreadable: Expecting property name enclosed in double quotes
database file changed on disk before COMMIT: True
rollback journal next to it: True
after reopening: 0 of 1,000 marks changed
rollback journal still there: False
database file identical to before the update: True

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 crash_midway.py

The plain file is ruined. Opening a file for writing empties it at once, and the program died after writing half of the new text, so 8,000 of the 16,000 characters are left: the old marks are gone and only half of the new ones arrived. The JSON reader cannot even parse what is left.

The SQLite database is untouched, and not because nothing reached the disk. The program set a tiny page cache (10 pages) and allowed SQLite to spill changed pages into the database file before the transaction ended, so the file on disk really was half-updated when the program died. Before SQLite changes a page, it copies the page’s original content into a rollback journal: A record of original database pages kept so SQLite can restore an unfinished transaction after an interruption. next to the database. The next connection to read the database found that journal, wrote the original pages back and deleted it: no mark changed, and the file is byte for byte what it was before the update, as the matching SHA-256 fingerprints show.

An update that happens completely or not at all is called atomic change: A change whose outcome is complete or absent, so an interrupted transaction does not leave only part of its intended update committed.. Careful programs can get atomic replacement of a single file by writing a new copy and renaming it over the old one: Python’s os.replace documents that a successful rename is atomic. A DBMS gives the same guarantee for a change that touches many rows of many tables, while other users keep working. SQLite does it with a rollback journal or a write-ahead log; the module on logging and recovery explains both.

Track the complete 1000-mark crash drill, from the JSON half-document to the recovered database:

Interactive · stage by stage The file and database after the complete crash drill Track the actual 1000 marks, the half-written text and recovery of the spilled database pages.
The file and database after the complete crash drill, step 6 of 6. Showing Plain JSON file, Changed DB pages, Rollback journal, Next connection. In focus: Next connection.Plain JSON fileChanged DB pagesRollback journalNext connection

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Prepare 1000 marks. The program creates 1000 marks from 40 through 89. Its JSON representation has 16,000 characters; the SQLite rows also include 300-character remarks.
  2. The JSON writer stops. The child writes only 8,000 characters of the new JSON text, flushes them and exits without cleanup. The old complete file has been replaced by an incomplete document.
  3. SQLite spills changed pages. The database child starts a transaction, raises every mark by 5 and uses a 10-page cache with spilling enabled. Before COMMIT, changed pages have reached the database file.
  4. The journal keeps originals. SQLite saved the original pages in its rollback journal before overwriting them. The output confirms both a changed database fingerprint and a journal beside it.
  5. The next read recovers. After the child exits before COMMIT, the next connection restores the original pages from the journal. None of the 1000 marks has changed.
  6. Compare complete outcomes. The JSON reader cannot parse its half-document. The recovered database is byte-identical to its original file and its rollback journal has been removed.

Checkpoint

Check: Recover the whole update

  1. Question 1 of 2 How many characters remain in the interrupted JSON file?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 8000

    The remaining half cannot be parsed as a complete JSON document.

  2. Question 2 of 2 The database fingerprint changed before COMMIT. Why can the next connection still restore the original state?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The journal retains the original pages

    The output shows changed disk bytes, a journal, zero changed marks after reopening and an identical final database file.

Constraints reject each invalid row

When the rules are part of the schema, the DBMS checks them on every write, whichever program sends it. This table of marks accepts a mark only for a student who exists, only between 0 and 100, and only once per student and subject:

Rules the database enforces SQL · rules.sql
-- The rules live in the schema, so the database checks them on every write,
-- whichever program sends it.
PRAGMA foreign_keys = ON;   -- SQLite checks foreign keys only when this is switched on

CREATE TABLE students (
  roll TEXT PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE marks (
  roll    TEXT NOT NULL REFERENCES students (roll),
  subject TEXT NOT NULL,
  mark    INTEGER NOT NULL CHECK (mark BETWEEN 0 AND 100),
  PRIMARY KEY (roll, subject)
);

INSERT INTO students VALUES ('21CS0001', 'Asha'), ('21CS0002', 'Ravi');
INSERT INTO marks VALUES ('21CS0001', 'DBMS', 78);

INSERT INTO marks VALUES ('21CS0002', 'DBMS', 140);  -- a mark out of range
INSERT INTO marks VALUES ('21CS0099', 'DBMS', 65);   -- a student who does not exist
INSERT INTO marks VALUES ('21CS0001', 'DBMS', 81);   -- a second DBMS mark for Asha
INSERT INTO students VALUES ('21CS0003', NULL);      -- a student without a name

SELECT * FROM marks;

Output (exit status 1)

┌──────────┬─────────┬──────┐
│   roll   │ subject │ mark │
├──────────┼─────────┼──────┤
│ 21CS0001 │ DBMS    │ 78   │
└──────────┴─────────┴──────┘

Printed as an error (standard error)

Runtime error near line 19: CHECK constraint failed: mark BETWEEN 0 AND 100
Runtime error near line 20: FOREIGN KEY constraint failed
Runtime error near line 21: UNIQUE constraint failed: marks.roll, marks.subject
Runtime error near line 22: NOT NULL constraint failed: students.name

Recorded with sql.js 1.14.2 (SQLite 3.49.1) on macOS 26 arm64. To run it yourself: sqlite3 -box :memory: < rules.sql

Four bad rows were sent and four were refused, each with the name of the rule it broke: the CHECK on the range, the FOREIGN KEY to students, the UNIQUE combination of roll number and subject (the primary key), and NOT NULL on the name. Only the valid mark remains. One SQLite detail matters here: foreign keys are checked only after PRAGMA foreign_keys = ON, which every connection must run for itself, because the check is off by default for compatibility with old applications.

Choose the rule behind each refusal before reading the surviving mark:

Interactive · stage by stage Four invalid rows are refused, one mark remains Identify the schema rule behind each error before looking at the stored row.
Four invalid rows are refused, one mark remains, step 6 of 6. Showing Rules in the schema, Candidate row, Stored marks. In focus: Stored marks.Rules in the schemaCandidate rowStored marks

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Enable foreign keys. The connection runs PRAGMA foreign_keys = ON. Students and marks then carry the same range, reference, uniqueness and required-name rules used by the following writes.
  2. Reject the mark 140. The DBMS mark for roll 21CS0002 is 140. Its CHECK requires a value between 0 and 100, so the row is refused.
  3. Reject an unknown student. Roll 21CS0099 is absent from students. The attempted mark 65 is refused by the foreign key even though its value is within range.
  4. Reject the duplicate mark. A second DBMS mark 81 is attempted for roll 21CS0001. The existing mark 78 already owns that roll-and-subject primary key.
  5. Reject a missing name. The new student 21CS0003 has a NULL name. NOT NULL refuses the student independently of web-app validation.
  6. Read the surviving row. The final marks result contains only roll 21CS0001, subject DBMS and mark 78. Every invalid attempt has left that valid row in place.

Checkpoint

Check: Rules on every write

  1. Question 1 of 2 How many bad rows are refused by rules.sql?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 4

    Identify the four separate failures before reading the surviving mark 78.

  2. Question 2 of 2 A mark of 65 names roll 21CS0099, which is absent. Which rule refuses it?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Foreign key

    Value validity and relationship validity are different schema rules.

Privileges limit columns for each role

A file’s permissions apply to the whole file. A client-server DBMS grants database privilege: An authorisation allowing a database role to perform a specified operation on an object or its selected columns. on tables, views and even single columns, to users and to groups of users. In PostgreSQL, for example, GRANT SELECT (roll, hostel, room) ON students TO warden grants SELECT on those three columns. With no broader direct, inherited or PUBLIC privileges, the warden can read those columns without marks; the narrow grant does not revoke existing access. SQLite has no GRANT or REVOKE at all: it is a library that reads an ordinary file, so its documentation explains that only the operating system’s file permissions apply. That is one reason SQLite describes itself as storage for one application or device rather than a store that many users share over a network.

Compare the warden’s three permitted columns with the SQLite file boundary:

Interactive · stage by stage The warden sees rooms rather than marks Compare column privileges with whole-file permissions on the college fields.
The warden sees rooms rather than marks, step 3 of 3. Showing Warden role, Roll, hostel, room, Whole SQLite file. In focus: Whole SQLite file.Warden roleRoll, hostel, roomWhole SQLite file

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. Name the reading role. The warden needs room-allotment data but does not need marks. Keep the access requirement separate from the table layout.
  2. Grant the required columns. The PostgreSQL SELECT grant on roll, hostel and room lets that role read the three granted columns. It does not grant the marks column.
  3. Recognise the file boundary. SQLite has no GRANT or REVOKE service. Its ordinary database file is protected by operating-system permissions, so that deployment has a different access boundary.

Checkpoint

Check: Limit each role

  1. Question 1 of 2 Which columns appear in the PostgreSQL grant to the warden?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: roll, hostel and room

    A column grant can be narrower than whole-file permission.

  2. Question 2 of 2 Room numbers and marks stay in the same table. What preserves the warden's narrower reading requirement?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Column or suitable-view privileges

    Separating access requirements from physical storage avoids granting unrelated fields.

A catalog and three schema levels describe the same database

The catalog stores schema as queryable rows

The database schema: The description of database objects and rules, including tables, columns, keys, constraints, views and indexes. describes the data: the tables, their columns and types, the keys and constraints, the views and the indexes. It changes rarely. The database instance: The data held by a database at one particular moment, changing as rows are inserted, updated or deleted., also called the state of the database, is the data the database holds at one moment, and every insert, update and delete changes it.

A DBMS stores its schema as data too, in tables known as the database catalog: Database objects that describe the schema as data, so programs can query information about tables, columns, views and indexes. or data dictionary, and you query it like any other table. SQLite keeps one row per table, index, view and trigger in sqlite_schema (older programs use its other name, sqlite_master), with the CREATE statement that would rebuild the object:

The schema, stored as data SQL · catalog.sql
CREATE TABLE students (
  roll   TEXT PRIMARY KEY,
  name   TEXT NOT NULL,
  hostel TEXT
);
CREATE INDEX students_by_hostel ON students (hostel);
CREATE VIEW hostel_list AS SELECT hostel, name FROM students;

-- The schema itself is stored as rows of a table, and you query it like any other table.
SELECT type, name, tbl_name, sql FROM sqlite_schema;

Output

┌───────┬─────────────────────────────┬─────────────┬──────────────────────────────────────────────────────────────┐
│ type  │            name             │  tbl_name   │                             sql                              │
├───────┼─────────────────────────────┼─────────────┼──────────────────────────────────────────────────────────────┤
│ table │ students                    │ students    │ CREATE TABLE students (                                      │
│       │                             │             │   roll   TEXT PRIMARY KEY,                                   │
│       │                             │             │   name   TEXT NOT NULL,                                      │
│       │                             │             │   hostel TEXT                                                │
│       │                             │             │ )                                                            │
├───────┼─────────────────────────────┼─────────────┼──────────────────────────────────────────────────────────────┤
│ index │ sqlite_autoindex_students_1 │ students    │                                                              │
├───────┼─────────────────────────────┼─────────────┼──────────────────────────────────────────────────────────────┤
│ index │ students_by_hostel          │ students    │ CREATE INDEX students_by_hostel ON students (hostel)         │
├───────┼─────────────────────────────┼─────────────┼──────────────────────────────────────────────────────────────┤
│ view  │ hostel_list                 │ hostel_list │ CREATE VIEW hostel_list AS SELECT hostel, name FROM students │
└───────┴─────────────────────────────┴─────────────┴──────────────────────────────────────────────────────────────┘

Recorded with sql.js 1.14.2 (SQLite 3.49.1) on macOS 26 arm64. To run it yourself: sqlite3 -box :memory: < catalog.sql

Three details are worth noticing. The primary key created an index of its own, sqlite_autoindex_students_1, and its sql column is empty because no statement of yours created it. For an index, tbl_name names the indexed table, here students. For the view, tbl_name is its own name, hostel_list; the stored query names the table it reads. And the stored text is your own statement, line breaks and all, with only small normalisations such as the capitals of its first keywords.

PostgreSQL offers two catalogs. The information schema is a set of views defined by the SQL standard, so the same queries work on other systems; the view information_schema.columns, for example, lists the columns of every table you are allowed to see. The system catalogs live in the schema pg_catalog, which every PostgreSQL database contains; they are PostgreSQL’s own tables and also describe the features the standard does not know about. Its documentation warns that they are regular tables you could damage by hand, and that commands such as CREATE DATABASE are the way to change them: that command inserts a row into the catalog pg_database and creates the database on disk.

Read all four objects by type and distinguish an index’s table from the view’s own name:

Interactive · stage by stage The four schema rows created by catalog.sql Read the type, name, table-name field and SQL for every object, including the view.
The four schema rows created by catalog.sql, step 4 of 4. Showing students table, Primary-key index, Hostel index, hostel_list view. In focus: hostel_list view.students tablePrimary-key indexHostel indexhostel_list view

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. The table records its SQL. The students row has type table, name students and tbl_name students. Its sql value holds the CREATE TABLE statement.
  2. The primary key adds an index. sqlite_autoindex_students_1 is an index on students. SQLite made it for the TEXT primary key, so no user CREATE INDEX statement is stored in its sql field.
  3. The index names its table. students_by_hostel also has tbl_name students. Its sql value describes the CREATE INDEX statement on hostel.
  4. The view names itself. hostel_list has type view and tbl_name hostel_list, its own name. The SELECT in its CREATE VIEW text identifies the students table.

Checkpoint

Check: Catalog and schema descriptions

  1. Question 1 of 2 Which catalog field stores the SQL that recreates hostel_list?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: sql

    Read each catalog field according to the object type and its role.

  2. Question 2 of 2 The catalog result has one table, two indexes and one view. How many rows should the index exercise return from that schema?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 2

    Filter on type index while retaining both kinds of index row.

Views, one schema and storage stay separate

The standard way to describe how a DBMS separates users from storage is the three-schema architecture, with one level for each kind of description:

Three levels of a database: user views on top, one logical schema in the middle, storage at the bottom.External level: viewsConceptual level: one logical schemastudents, allotments, markswith types, keys and constraintsInternal level: how it is storedfiles and pages, B-tree indexes,record layout, page sizeOffice view: roll, name, feesWarden view: roll, hostel, roomResults view: roll, subject, marklogical data independence:change the schema, keep the viewsphysical data independence:change the storage, keep the schema

The three-schema architecture and the two kinds of data independence

Text description of the diagram

The diagram is a column of three levels, from what users see at the top to how the data is stored at the bottom.

  1. External level: views, one for each group of users. The office sees roll number, name and fees; the warden sees roll number, hostel and room; the results page sees roll number, subject and mark.
  2. Conceptual level: one logical schema for the whole database, with the tables students, allotments and marks and their types, keys and constraints.
  3. Internal level: how the data is stored, as files and pages, B-tree indexes, the layout of each record and the page size.

The arrow from the external to the conceptual level is labelled "logical data independence: change the schema, keep the views". The arrow from the conceptual to the internal level is labelled "physical data independence: change the storage, keep the schema".

  • The external level holds the views that groups of users work with. The warden sees rooms, the office sees fees, and neither needs the rest.
  • The conceptual level, or logical level, holds one schema for the whole database: every table, column, type, key and constraint.
  • The internal level, or physical level, describes storage: files and pages, indexes, the layout of each record.

The DBMS maps each level onto the one below it, and those mappings are what make data independence possible, the ability to change one level without rewriting what sits above it:

  • physical data independence: The ability to change physical storage or access choices while retaining the logical schema and application queries. means you can change the internal level, by adding an index, reorganising files or moving to a faster disk, without changing the logical schema or the programs. E. F. Codd’s 1970 paper that introduced the relational model opens with exactly this aim: users and most programs should not have to know how the data is organised inside the machine, and should keep working when that organisation changes.
  • logical data independence: The ability to change the logical schema while preserving the external reading interfaces that applications use. means you can change the logical schema, by splitting a table or adding a column, without breaking the views and the programs that use them. PostgreSQL’s tutorial makes the same point about views: they hide the structure of your tables, which may change as an application evolves, behind interfaces that stay the same.

Keep the whole-structure diagram, then follow the mappings that absorb each kind of change:

Interactive · stage by stage Views, the logical schema and physical storage Keep user interfaces apart from the schema and the storage choices underneath them.
Views, the logical schema and physical storage, step 5 of 5. Showing External views, One logical schema, Physical storage. In focus: External views.External viewsOne logical schemaPhysical storage

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Readers need different views. The office sees roll, name and fees; the warden sees roll, hostel and room; the results page sees roll, subject and mark. These are external descriptions.
  2. The schema holds common rules. Students, allotments and marks share one conceptual description of tables, types, keys and constraints. The views use different portions of that description.
  3. Storage chooses the layout. Files, pages, B-tree indexes and record layouts belong to the internal level. An application query need not name these choices to read its result.
  4. Change storage below the schema. Physical data independence preserves the logical schema while an index or file layout changes. The mapping to storage absorbs that change.
  5. Change the schema beneath views. Logical data independence preserves the reading interface when tables change. It needs suitable mappings and cannot recreate information that was removed.

Checkpoint

Check: Catalog and schema descriptions

  1. Question 1 of 2 Files, pages and record layout belong to which level?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Internal

    Distinguish the storage description from both a view and the logical tables.

  2. Question 2 of 2 A table split preserves the old reports through a view. Which separation does it use?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: External views from the conceptual schema

    Mappings can preserve the external reading shape only while the necessary information remains available.

An index changes the plan without changing rows

EXPLAIN QUERY PLAN asks SQLite how it would run a query, without running it. Its detail column is the part to read: SCAN means every row of the table is visited, and SEARCH means only some rows are, found through an index.

A new index changes the plan, not the answer SQL · physical_independence.sql
CREATE TABLE students (roll TEXT PRIMARY KEY, name TEXT NOT NULL, hostel TEXT);
INSERT INTO students VALUES
  ('21CS0001', 'Asha', 'Kaveri'),
  ('21CS0002', 'Ravi', 'Godavari'),
  ('21CS0003', 'Meera', 'Kaveri');

-- The query, and how the engine plans to run it, before the index exists.
EXPLAIN QUERY PLAN SELECT name FROM students WHERE hostel = 'Kaveri' ORDER BY name;
SELECT name FROM students WHERE hostel = 'Kaveri' ORDER BY name;

-- A change at the storage level: a new index.
CREATE INDEX students_by_hostel ON students (hostel);

-- The same query text: a different plan, the same result.
EXPLAIN QUERY PLAN SELECT name FROM students WHERE hostel = 'Kaveri' ORDER BY name;
SELECT name FROM students WHERE hostel = 'Kaveri' ORDER BY name;

Output

┌────┬────────┬─────────┬──────────────────────────────┐
│ id │ parent │ notused │            detail            │
├────┼────────┼─────────┼──────────────────────────────┤
│ 3  │ 0      │ 216     │ SCAN students                │
│ 11 │ 0      │ 0       │ USE TEMP B-TREE FOR ORDER BY │
└────┴────────┴─────────┴──────────────────────────────┘
┌───────┐
│ name  │
├───────┤
│ Asha  │
│ Meera │
└───────┘
┌────┬────────┬─────────┬───────────────────────────────────────────────────────────┐
│ id │ parent │ notused │                          detail                           │
├────┼────────┼─────────┼───────────────────────────────────────────────────────────┤
│ 4  │ 0      │ 62      │ SEARCH students USING INDEX students_by_hostel (hostel=?) │
│ 13 │ 0      │ 0       │ USE TEMP B-TREE FOR ORDER BY                              │
└────┴────────┴─────────┴───────────────────────────────────────────────────────────┘
┌───────┐
│ name  │
├───────┤
│ Asha  │
│ Meera │
└───────┘

Recorded with sql.js 1.14.2 (SQLite 3.49.1) on macOS 26 arm64. To run it yourself: sqlite3 -box :memory: < physical_independence.sql

Before the index, SQLite scans the whole table; after it, it searches the index for hostel = 'Kaveri'. Both times it sorts the result for ORDER BY in a temporary B-tree, and both times the answer is Asha and Meera. Not a word of the query changed. That is physical data independence, and it is the everyday kind: database administrators add and drop indexes on live systems, and the programs never notice, apart from the speed.

Read both complete plans and confirm that they still return Asha and Meera:

Interactive · stage by stage A different access path returns Asha and Meera Compare both complete query plans and both results of physical_independence.sql.
A different access path returns Asha and Meera, step 5 of 5. Showing Same query text, Access path, Asha and Meera. In focus: Asha and Meera.Same query textAccess pathAsha and Meera

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Read before the index. The query selects names in hostel Kaveri and orders by name. With no hostel index, its plan scans students.
  2. Sort the first result. The plan uses a temporary B-tree for ORDER BY. The result names are Asha and Meera.
  3. Add the hostel index. CREATE INDEX students_by_hostel changes the access choices. The query text and logical columns stay the same.
  4. Search after the index. The new plan searches students_by_hostel for hostel rather than scanning every student. Its ORDER BY still uses a temporary B-tree.
  5. Compare both answers. The second result is still Asha and Meera in name order. The changed plan preserves the reading interface.

Checkpoint

Check: Change storage only

  1. Question 1 of 2 Which plan uses students_by_hostel for a SEARCH?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The plan after CREATE INDEX

    The same query text lets the planner consider the new access path.

  2. Question 2 of 2 Did adding students_by_hostel remove ORDER BY's temporary B-tree in the original run?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: No, both plans still sort

    Read the complete plan rather than assuming the new SEARCH removed every other step.

A view keeps reads working after a table split

This time the logical schema changes. Hostel rooms move out of students into a table of their own, and a view with the old name puts the old shape back together:

A view keeps the old shape SQL · logical_independence.sql
-- Version 1 of the schema: hostel rooms are columns of students.
CREATE TABLE students (roll TEXT PRIMARY KEY, name TEXT NOT NULL, hostel TEXT, room INTEGER);
INSERT INTO students VALUES
  ('21CS0001', 'Asha', 'Kaveri', 101),
  ('21CS0002', 'Ravi', 'Godavari', 214),
  ('21CS0003', 'Meera', NULL, NULL);

-- A report that programs already run:
SELECT name, hostel, room FROM students ORDER BY roll;

-- Version 2: room allotments move to a table of their own...
CREATE TABLE student (roll TEXT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE allotment (
  roll   TEXT PRIMARY KEY REFERENCES student (roll),
  hostel TEXT NOT NULL,
  room   INTEGER NOT NULL
);
INSERT INTO student SELECT roll, name FROM students;
INSERT INTO allotment SELECT roll, hostel, room FROM students WHERE hostel IS NOT NULL;
DROP TABLE students;

-- ...and a view keeps the old shape under the old name.
CREATE VIEW students AS
  SELECT s.roll, s.name, a.hostel, a.room
  FROM student AS s LEFT JOIN allotment AS a ON a.roll = s.roll;

-- The old report runs unchanged and returns the same rows:
SELECT name, hostel, room FROM students ORDER BY roll;

-- But a program that writes to the old shape now fails:
INSERT INTO students VALUES ('21CS0004', 'Kiran', 'Kaveri', 102);

Output (exit status 1)

┌───────┬──────────┬──────┐
│ name  │  hostel  │ room │
├───────┼──────────┼──────┤
│ Asha  │ Kaveri   │ 101  │
│ Ravi  │ Godavari │ 214  │
│ Meera │          │      │
└───────┴──────────┴──────┘
┌───────┬──────────┬──────┐
│ name  │  hostel  │ room │
├───────┼──────────┼──────┤
│ Asha  │ Kaveri   │ 101  │
│ Ravi  │ Godavari │ 214  │
│ Meera │          │      │
└───────┴──────────┴──────┘

Printed as an error (standard error)

Parse error near line 31: cannot modify students because it is a view

Recorded with sql.js 1.14.2 (SQLite 3.49.1) on macOS 26 arm64. To run it yourself: sqlite3 -box :memory: < logical_independence.sql

The report that read students runs unchanged and returns the same three rows, now from two tables. The last statement shows the limit. A program that inserted into students now fails, because a view in SQLite is read-only; writes through it need INSTEAD OF triggers that send each change to the right table. PostgreSQL would refuse the insert too: it updates a view automatically only when the view reads exactly one table, and this one joins two.

This is why logical data independence is the harder kind. Views hide changes from readers well, from writers only with extra work, and some changes they cannot hide at all: once a column is dropped, no view can bring its values back.

Keep Meera’s missing allotment in the result, then follow the failed insert through the old name:

Interactive · stage by stage A three-row reading interface survives a table split Keep Meera in the result, then explain the final insert failure through the old name.
A three-row reading interface survives a table split, step 5 of 5. Showing students table, student + allotment, students view, Insert through view. In focus: Insert through view.students tablestudent + allotmentstudents viewInsert through view

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Read the original three rows. Students contains Asha in Kaveri 101, Ravi in Godavari 214 and Meera without a hostel or room. The report reads all three in roll order.
  2. Separate students and allotments. Student keeps all three people. Allotment gets the two rows whose hostel is present, so the split does not invent a room for Meera.
  3. Rebuild the reading shape. The students view LEFT JOINs the new tables. The same report returns the same three rows, including Meera with empty hostel and room values.
  4. Try the old writing interface. The last statement inserts Kiran through students. SQLite refuses it because students is now a view, so preserving reads has not preserved that write.
  5. State the limit explicitly. INSTEAD OF triggers or changed application writes are needed for the new schema. A view cannot restore a dropped column's values.

Checkpoint

Check: Keep the reading interface

  1. Question 1 of 2 Which old name does the split's view retain?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: students

    Keeping the old reading name is one part of preserving the application interface.

  2. Question 2 of 2 Meera has no allotment. Why does the rebuilt report still contain her?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The view uses LEFT JOIN from student

    The original three-row reading result is preserved without inventing data; the later insert still needs a writing plan.

A statement class does not decide rollback behavior

SQL statements are usually grouped into four classes:

Class What it does Typical statements
DDL, data definition language Defines and changes the schema CREATE, ALTER, DROP
DML, data manipulation language Reads and changes the rows SELECT, INSERT, UPDATE, DELETE
DCL, data control language Gives and takes away privileges GRANT, REVOKE
TCL, transaction control language Groups statements into transactions BEGIN, COMMIT, ROLLBACK, SAVEPOINT

These four names are a teaching convention, and the manuals of real systems draw the lines differently. Oracle Database’s SQL reference lists GRANT, REVOKE and TRUNCATE as DDL, counts SELECT as DML, and adds classes for session control and system control. MySQL’s manual says that TRUNCATE TABLE, although it empties a table much as DELETE does, is a DDL statement. Some textbooks give SELECT a class of its own, DQL, for data query language. For an exam, use the four classes above; for real work, check what your own DBMS does with each statement.

The difference matters most for transactions. In SQLite, DDL takes part in the transaction it runs in, so a ROLLBACK undoes a CREATE TABLE:

CREATE TABLE inside a transaction SQL · ddl_rollback.sql
-- In SQLite, CREATE TABLE is part of the transaction it runs in.
BEGIN;
CREATE TABLE notices (id INTEGER PRIMARY KEY, body TEXT NOT NULL);
INSERT INTO notices (body) VALUES ('The DBMS lab moves to room 204');
SELECT name AS tables_inside_the_transaction FROM sqlite_schema WHERE type = 'table';
ROLLBACK;

SELECT count(*) AS tables_after_rollback FROM sqlite_schema WHERE type = 'table';

Output

┌───────────────────────────────┐
│ tables_inside_the_transaction │
├───────────────────────────────┤
│ notices                       │
└───────────────────────────────┘
┌───────────────────────┐
│ tables_after_rollback │
├───────────────────────┤
│ 0                     │
└───────────────────────┘

Recorded with sql.js 1.14.2 (SQLite 3.49.1) on macOS 26 arm64. To run it yourself: sqlite3 -box :memory: < ddl_rollback.sql

PostgreSQL behaves the same way for most DDL. Its manual says, for example, that TRUNCATE is rolled back if the transaction around it does not commit, and the few commands that cannot run inside a transaction at all, such as CREATE DATABASE, say so on their own manual pages. MySQL behaves differently. Statements such as CREATE TABLE, ALTER TABLE, DROP TABLE and TRUNCATE TABLE end any open transaction with an implicit commit, and Oracle Database commits before and after every DDL statement. A migration script that mixes schema changes and data changes can therefore be all or nothing on PostgreSQL and SQLite, but not on MySQL or Oracle Database.

Walk through the definition and notice inside the transaction, then read the final catalog count:

Timeline · 4 events in order The notices table disappears with ROLLBACK Walk through the four phases of the SQLite transaction.
  1. BEGIN

    Start the transaction

    The script begins a transaction before creating any table.

  2. CREATE

    Define notices inside it

    CREATE TABLE notices defines id and body. The catalog query inside the transaction can see the table.

  3. INSERT

    Add the room 204 notice

    The script inserts its DBMS-lab notice. The data and schema changes are still part of the open transaction.

  4. ROLLBACK

    Undo data and definition

    ROLLBACK removes the table created inside the transaction. The final catalog count is 0; its statement class alone did not decide the rollback behavior.

The timeline has 4 events, from BEGIN to ROLLBACK.

Checkpoint

Check: Classes and rollback

  1. Question 1 of 2 In the four-class teaching scheme, what kind of statement is SAVEPOINT?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: TCL

    Keep the teaching classification separate from each engine's transaction behavior.

  2. Question 2 of 2 What proves that this SQLite CREATE TABLE was part of the rolled-back transaction?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The final table count is 0

    The recorded behavior, not the DDL label alone, establishes the outcome.

Database work connects requirements to data models

Database roles assign work and privileges

Several groups of people use the same database in different ways:

  • End users work through applications and never write SQL: a student checking results, a warden allotting rooms.
  • Application developers write the programs that send SQL, and the tests for them.
  • Database designers decide the schema: the tables, keys and constraints. The ER model and normalisation, later in this track, are their tools.
  • Database administrators (DBAs) run the system: they create users, grant privileges, plan backups and recovery, watch performance and upgrade versions.
  • Analysts query the data directly to answer questions, often on a read-only copy.

In PostgreSQL, each of these people, or the application acting for them, connects as a role. A role can be a single user or a group of users, can own tables and other objects, and can grant privileges on them to other roles. In a small team one person often plays several of these parts.

Assign each college task to a responsibility rather than assuming one person has one job:

Interactive · stage by stage Five kinds of work share one database Assign the college tasks to the people who carry them out.
Five kinds of work share one database, step 5 of 5. Showing End users, App developers, DB designers, DB administrators, Analysts. In focus: Analysts.End usersApp developersDB designersDB administratorsAnalysts

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Use an application. A student reads results and the warden allots rooms through an application. End users need not write its SQL.
  2. Build requests and tests. Developers write the SQL-sending programs and tests for their behavior. A transaction still needs the right read-and-write boundary in that code.
  3. Define the shared schema. Designers choose tables, keys and constraints. Their choices determine which data relationships the DBMS can enforce.
  4. Operate and recover the system. Administrators manage users and privileges, backups, recovery, performance and upgrades. That work differs from defining the schema or querying a report.
  5. Ask a reporting question. Analysts query data for an answer, often on a read-only copy. One person can perform several jobs; PostgreSQL roles group privileges rather than job titles.

Checkpoint

Check: Database work and data models

  1. Question 1 of 2 Who queries the data directly for a reporting answer, often on a read-only copy?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Analyst

    Several kinds of work use one database; a small team can combine the jobs.

  2. Question 2 of 2 Who must arrange the application's safe read-and-write transaction in its SQL-sending code?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Application developer

    The original SQLite failure shows why application logic remains a separate responsibility.

Six data models separate record shape from access

A data model: The concepts a database offers for describing records, their relationships and the operations used to read or change them. is the set of ideas a DBMS gives you for describing data: what a record looks like, how records refer to each other and which operations exist. Six models cover nearly every database you will meet:

  • Relational: tables of rows with typed columns. Keys link the tables, and SQL combines them with joins. PostgreSQL, MySQL, SQLite, Microsoft SQL Server and Oracle Database are relational.
  • Document: each record is a document of fields and values, which can nest other documents and arrays. MongoDB stores documents in BSON, a binary form of JSON.
  • Key-value: you store a value under a key and fetch it by that key. Redis is a widely used example, with values that can be strings, hashes, lists, sets and other structures.
  • Wide-column: rows are grouped into partitions, and a hash of each row’s partition key decides which machine stores it, so one table spreads across many machines. Apache Cassandra works this way.
  • Graph: nodes and the relationships between them, both with properties, and queries that follow paths. Even the SQL standard now has a part for it, Property Graph Queries (SQL/PGQ).
  • Vector: each item is stored with an embedding, a long list of numbers, and queries look for the nearest neighbours by distance. The pgvector extension adds this to PostgreSQL.

For an application that records business events such as orders, bookings, marks or payments, the relational model is the sensible default: it checks rules, joins freely and runs transactions. Choose another model when one access pattern clearly needs it. The system design track compares the models by access pattern in Choosing a data model.

How widely each one is used is a different question from how good it is. In the 2025 Stack Overflow Developer Survey, the databases that the most respondents had done extensive work with in the past year were PostgreSQL (55.6% of the 26,083 who answered), MySQL (40.5%) and SQLite (37.5%), ahead of Microsoft SQL Server (30.1%), Redis (28%) and MongoDB (24%). Many projects use more than one.

The first database systems were hierarchical or network systems: records were linked into trees or more general networks, and a program found data by following those links in the order the structure allowed. When the structure changed, the programs had to change with it. Codd’s paper of 1970 proposed something else: data as relations, which are tables, described only by their contents, so that programs depend on what the data means rather than on how it is stored. Relational systems and SQL followed. SQL is now an international standard, ISO/IEC 9075 “Database Language SQL”, revised every few years; PostgreSQL 18 measures its conformance against the 2023 revision, SQL:2023.

GATE CS

The GATE 2027 syllabus for Computer Science and Information Technology lists Databases as Section 9: the ER model, the relational model (relational algebra, tuple calculus and SQL), integrity constraints, normal forms, file organisation, indexing with B and B+ trees, and transactions and concurrency control (GATE 2027 syllabus). This lesson’s integrity, concurrency and recovery examples are a first look at three of those topics.

SQLite Online (SQL Playground) Run this lesson's SQL on a SQLite database in your browser, or open a .db file and query its sqlite_schema table. SQL to ER Diagram Paste CREATE TABLE statements, such as the ones in this lesson, to see the schema drawn as an ER diagram.

Compare all six record shapes by their operations before using the product examples:

Interactive · stage by stage Six data models and their access patterns Choose a record shape and operation before choosing the product name.
Six data models and their access patterns, step 6 of 6. Showing Relational, Document, Key-value, Wide-column, Graph, Vector. In focus: Vector.RelationalDocumentKey-valueWide-columnGraphVector

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Relational tables and joins. Rows have typed columns and keys connect tables. The college records use the rules and transactions that make this a useful business-data default.
  2. Document fields can nest. A document keeps fields and values together and can nest arrays or other documents. MongoDB stores BSON rather than plain JSON text.
  3. A key names one value. Key-value access stores a value under a key and fetches it with that key. Redis supports strings, hashes, lists, sets and other value structures.
  4. Partitions distribute rows. Wide-column storage groups rows into partitions. In Cassandra, the partition-key hash helps decide which machine stores a partition.
  5. Relationships support paths. A graph models nodes and relationships, with properties on each. Queries follow relationships rather than treating a product name as the model.
  6. Embeddings support distance. Vector storage associates an item with an embedding and searches for neighbours by distance. pgvector adds this access pattern to PostgreSQL.

Checkpoint

Check: Database work and data models

  1. Question 1 of 2 Which named model groups rows into partitions spread across machines?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Wide-column

    A data model names its structure and operations rather than a particular product alone.

  2. Question 2 of 2 The college needs related marks and enrolments with constraints and transactions. Which model is the section's default?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Relational

    Begin with the data and operations, then justify a different model when its access pattern is needed.

Practise

Exercise · Easy · SQL

List every index with the table it belongs to

A database's schema is stored in its catalog, and in SQLite you can query it like any table. Write a query on sqlite_schema that returns one row for every index of the database, in two columns:

  • index_name: the name of the index;
  • table_name: the table the index belongs to.

Include the indexes that SQLite creates by itself for PRIMARY KEY and UNIQUE constraints, and leave out tables, views and triggers. For a database made by

CREATE TABLE rooms (room_no INTEGER PRIMARY KEY, hostel TEXT NOT NULL, label TEXT UNIQUE);
CREATE INDEX rooms_by_hostel ON rooms (hostel);

the result would be:

┌──────────────────────────┬────────────┐
│        index_name        │ table_name │
├──────────────────────────┼────────────┤
│ sqlite_autoindex_rooms_1 │ rooms      │
│ rooms_by_hostel          │ rooms      │
└──────────────────────────┴────────────┘

The order of the rows does not matter. The sample tests run your query on two small databases of their own.

Starter code · query.sql

-- Return index_name and table_name for every index of the database.
SELECT name FROM sqlite_schema;
The sample tests · sample_tests.yaml
# Sample tests (public): each test builds its own schema in a fresh database, runs the learner's query and compares
# the result with the expected rows (the order of rows does not matter; column names must match).
tests:
  - name: lists the index of a primary key and an index created by hand
    setup: |
      CREATE TABLE students (roll TEXT PRIMARY KEY, name TEXT NOT NULL, hostel TEXT);
      CREATE INDEX students_by_hostel ON students (hostel);
      CREATE VIEW hostel_list AS SELECT hostel, name FROM students;
    expected:
      columns: [index_name, table_name]
      rows:
        - [sqlite_autoindex_students_1, students]
        - [students_by_hostel, students]
  - name: finds indexes on several tables and skips an INTEGER PRIMARY KEY, which needs no index
    setup: |
      CREATE TABLE courses (course_id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE, title TEXT NOT NULL);
      CREATE TABLE enrolments (
        student_id INTEGER NOT NULL,
        course_id  INTEGER NOT NULL REFERENCES courses (course_id),
        PRIMARY KEY (student_id, course_id)
      );
      CREATE INDEX enrolments_by_course ON enrolments (course_id);
      CREATE TRIGGER no_empty_code BEFORE INSERT ON courses WHEN NEW.code = '' BEGIN SELECT RAISE(ABORT, 'empty code'); END;
    expected:
      columns: [index_name, table_name]
      rows:
        - [sqlite_autoindex_courses_1, courses]
        - [sqlite_autoindex_enrolments_1, enrolments]
        - [enrolments_by_course, enrolments]
A hint

Every object of the schema is one row of sqlite_schema, and its type column says what it is: 'table', 'index', 'view' or 'trigger'. The name column holds the object's own name and tbl_name the table it belongs to; rename both with AS.

The sample tests run on this device, in your browser (sql.js): nothing is sent to mysmartcopilot.com. The first run downloads SQLite (about 0.7 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Practice that adapts to you

Practise this lesson

20 questions about 10 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 20 The hostel office and the warden both update fees.json. Each program reads the file, changes one student's balance and writes the whole file back. Now and then a payment disappears, with no error. Which DBMS service prevents this?

    Choose one answer.

    Show the answer: Question 1 of 20

    Answer: Concurrency control

    This is a lost update: both programs start from the same old version, and the one that saves last overwrites the other's change. A DBMS keeps simultaneous writers apart with transactions and locks, and an UPDATE that computes the new value itself (balance = balance + 500) reads and writes in one step.

  2. Question 2 of 20 A program that adds this month's mess charges to 2,000 student accounts loses power halfway. Afterwards, some accounts have the charge and some do not. Which DBMS service would have left either all accounts or none charged?

    Choose one answer.

    Show the answer: Question 2 of 20

    Answer: Recovery, which makes the update atomic

    An update that is interrupted must be undone completely or finished completely. The DBMS records what it changes in a journal or a write-ahead log, and after the crash it uses that record to put the database back to a consistent state, as the crash example in this lesson shows with SQLite's rollback journal.

  3. Question 3 of 20 The marks web app refuses any mark above 100, but a mark of 140 appears in the data after a bulk import by another script. What should hold the rule so that every program obeys it?

    Choose one answer.

    Show the answer: Question 3 of 20

    Answer: A CHECK constraint in the schema, such as CHECK (mark BETWEEN 0 AND 100)

    A rule in one program protects only that program's writes. As an integrity constraint in the schema, the DBMS checks it on every INSERT and UPDATE, whichever program sends it, and refuses the bad row with an error. An index or a view does not stop the row from being stored.

  4. Question 4 of 20 Room numbers and marks are both columns of one table. The warden must read room numbers but never marks. What does a client-server DBMS such as PostgreSQL offer that file permissions cannot?

    Choose one answer.

    Show the answer: Question 4 of 20

    Answer: Privileges on single columns or on a view, granted to the warden's role

    File permissions apply to the whole file. A client-server DBMS grants privileges on tables, views and single columns, for example GRANT SELECT (roll, hostel, room) ON students TO warden. A second copy would bring back the problem of redundant, inconsistent data.

  5. Question 5 of 20 A database administrator adds an index on students(hostel). The same queries now return the same rows faster, and no program was changed. Which kind of data independence is this?

    Choose one answer.

    Show the answer: Question 5 of 20

    Answer: Physical data independence

    An index belongs to the internal level, the way data is stored. Changing it changed the query plan (SCAN became SEARCH in this lesson's example) but not the logical schema, the query text or the result.

  6. Question 6 of 20 The students table is split into student and allotment, and a view named students joins them back together, so the old reports keep working. Which kind of data independence is this?

    Choose one answer.

    Show the answer: Question 6 of 20

    Answer: Logical data independence

    The logical schema changed, and the view keeps the external level the same for the programs that read it. It is the harder kind: in this lesson's example, a program that inserts into students fails, because the view is read-only.

  7. Question 7 of 20 In the four-class scheme of DDL, DML, DCL and TCL, which of these statements is DCL?

    Choose one answer.

    Show the answer: Question 7 of 20

    Answer: GRANT SELECT ON marks TO analyst

    GRANT and REVOKE give and take away privileges, which is data control. TRUNCATE is usually counted as DDL, SAVEPOINT is transaction control and SELECT is DML (some textbooks call it DQL). Real manuals differ: Oracle Database's SQL reference lists GRANT and REVOKE among its DDL statements.

  8. Question 8 of 20 In this lesson's lost-update example, SQLite lost an increment in one run and kept both in another. What made the difference?

    Choose one answer.

    Show the answer: Question 8 of 20

    Answer: The database computed n + 1 itself, in one UPDATE inside a write transaction

    The run that read the value with a SELECT and wrote back a value computed in Python lost an update in SQLite too. Only when the read and the write became one statement, run under SQLite's write lock inside BEGIN IMMEDIATE, did both increments count. timeout=0 only made the refusal visible instead of waiting for the lock.

  9. Question 9 of 20 What lets a DBMS apply a shared integrity rule to different writers?

    Choose one answer.

    Show the answer: Question 9 of 20

    Answer: All writes go through the database service

    The shared boundary lets the same CHECK reject a bad importer write as well as a web-app write.

  10. Question 10 of 20 Which statement requests the write transaction before the original counter arithmetic?

    Choose one answer.

    Show the answer: Question 10 of 20

    Answer: BEGIN IMMEDIATE

    A runs BEGIN IMMEDIATE, the arithmetic UPDATE and COMMIT before B starts its successful writing turn.

  11. Question 11 of 20 After SQLite reopens in the crash drill, how many of the 1000 marks changed?

    Type a number.

    Show the answer: Question 11 of 20

    Answer: 0 marks

    The journal restores the unfinished update. The output reports 0 changed marks and an identical database file.

  12. Question 12 of 20 What must rules.sql enable for its foreign-key refusal?

    Choose one answer.

    Show the answer: Question 12 of 20

    Answer: PRAGMA foreign_keys = ON

    The connection enables the rule before the attempted mark for the absent student 21CS0099.

  13. Question 13 of 20 What protects the ordinary SQLite database file in the original comparison?

    Choose one answer.

    Show the answer: Question 13 of 20

    Answer: Operating-system file permissions

    The PostgreSQL example grants three columns; the SQLite deployment has a whole-file access boundary.

  14. Question 14 of 20 Where does adding students_by_hostel change the three-schema architecture?

    Choose one answer.

    Show the answer: Question 14 of 20

    Answer: Internal level

    SCAN becomes SEARCH while both recorded queries return Asha and Meera.

  15. Question 15 of 20 What supplies the old students name for reading after the split?

    Choose one answer.

    Show the answer: Question 15 of 20

    Answer: A LEFT JOIN view

    The view preserves all three report rows but does not automatically preserve the insert interface.

  16. Question 16 of 20 How many tables does ddl_rollback.sql report after ROLLBACK?

    Type a number.

    Show the answer: Question 16 of 20

    Answer: 0 tables

    SQLite rolls back the CREATE TABLE inside this transaction along with its notice, leaving the final catalog count at 0.

  17. Question 17 of 20 For the two cases, select each correct answer. Case A: Why is sql blank for sqlite_autoindex_students_1 in the catalog result? Case B: Which level holds the warden's roll, hostel and room view?

    Choose every answer that is right.

    Show the answer: Question 17 of 20

    Answer:

    • Case A: SQLite created it for the primary key
    • Case B: External level

    Case A: The TEXT primary key caused SQLite to create an internal index without storing a user CREATE INDEX statement. Case B: The external descriptions differ for the office, warden and results page above one conceptual schema.

  18. Question 18 of 20 For the two cases, select each correct answer. Case A: The hostel_list view reads students. What is its tbl_name field in this SQLite catalog? Case B: A storage reorganisation preserves every table, constraint and view. Which mapping absorbs the change?

    Choose every answer that is right.

    Show the answer: Question 18 of 20

    Answer:

    • Case B: Conceptual schema to internal storage
    • Case A: hostel_list

    Case A: Object type decides the meaning: an index names its indexed table, while this view row names hostel_list. Case B: An internal reorganisation need not change the application queries that address the logical schema.

  19. Question 19 of 20 For the two cases, select each correct answer. Case A: Which role manages backups, recovery and upgrades? Case B: Which named model searches for neighbours by distance between embeddings?

    Choose every answer that is right.

    Show the answer: Question 19 of 20

    Answer:

    • Case B: Vector
    • Case A: Database administrator

    Case A: Designers choose the schema, developers write requests and administrators operate the database system. Case B: The lesson names pgvector as an extension that adds this pattern to PostgreSQL.

  20. Question 20 of 20 For the two cases, select each correct answer. Case A: One teammate designs marks constraints and another restores a failed database. Which jobs are these? Case B: An application chiefly follows paths between nodes, with properties on nodes and relationships. Which model expresses this shape?

    Choose every answer that is right.

    Show the answer: Question 20 of 20

    Answer:

    • Case A: Database design and administration
    • Case B: Graph

    Case A: One person may hold several responsibilities; the tasks still describe different kinds of database work. Case B: Use the operation and record shape to choose the model, while retaining relational tables as a useful default for the original business records.

Interview questions

Fresher · What is data independence, and which kind is harder to achieve?

Data independence is the ability to change how data is described at one level without changing what sits above it. Physical data independence lets you change storage, such as indexes, file organisation or disks, without changing the logical schema or the programs. Logical data independence lets you change the logical schema, such as splitting a table or adding a column, without breaking the external views and the programs that use them. Physical independence is easier and routine: adding an index changes the query plan but not the query text or its result. Logical independence is harder, because views can rebuild an old shape for reading, but writes through a view need extra work such as INSTEAD OF triggers, and a change that removes information cannot be hidden by any view.

Fresher · Is TRUNCATE a DDL or a DML statement?

It depends on the system, and that is the point to make. TRUNCATE empties a table, as a DELETE without a WHERE clause would, but MySQL’s manual and Oracle Database’s SQL reference both classify it as DDL. In MySQL it causes an implicit commit and cannot be rolled back, and it does not fire ON DELETE triggers. In PostgreSQL it is transaction-safe: a TRUNCATE inside a transaction that rolls back leaves the rows in place. So name the textbook class, then say what your own DBMS does with it, because that decides whether a script containing it can be undone.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A five-person team keeps customer orders as JSON files on a shared network drive, one file per day, changed by two scripts and a small web app. Which failures should they expect as the business grows, and how would you demonstrate each one before arguing for a database?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A wide customers table must be split into customers and customer_addresses. Twenty reports and three services read the table, and two of the services also write to it. How do you make the change without breaking any of them, and what can a view not hide?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A DBMS keeps the data and handles every access to it, which lets it enforce integrity, control concurrency, recover from crashes and decide who may see what: jobs that plain files leave to every program.
  • Lost updates come from reading, computing and writing in separate steps; let the database do the arithmetic inside a transaction (UPDATE … SET n = n + 1) and the update is safe.
  • A rollback journal or write-ahead log makes a change atomic: after a crash, the database is either fully updated or exactly as it was.
  • The catalog stores the schema as data: sqlite_schema in SQLite, information_schema and pg_catalog in PostgreSQL.
  • The three-schema architecture separates views, the logical schema and storage. Physical data independence is routine; logical data independence is harder, because views hide changes from readers more easily than from writers.
  • DDL, DML, DCL and TCL are textbook classes; real systems classify some statements differently and treat DDL inside transactions differently.

Terms in this lesson

atomic change
A change whose outcome is complete or absent, so an interrupted transaction does not leave only part of its intended update committed.
data model
The concepts a database offers for describing records, their relationships and the operations used to read or change them.
database catalog
Database objects that describe the schema as data, so programs can query information about tables, columns, views and indexes.
database instance
The data held by a database at one particular moment, changing as rows are inserted, updated or deleted.
database management system
Software that manages stored data and mediates requests to read or change it while providing integrity, concurrency, recovery and access services.
database privilege
An authorisation allowing a database role to perform a specified operation on an object or its selected columns.
database schema
The description of database objects and rules, including tables, columns, keys, constraints, views and indexes.
logical data independence
The ability to change the logical schema while preserving the external reading interfaces that applications use.
lost update
A change that is overwritten when another writer saves a value computed from an older read of the same data.
physical data independence
The ability to change physical storage or access choices while retaining the logical schema and application queries.
rollback journal
A record of original database pages kept so SQLite can restore an unfinished transaction after an interruption.

Corrections

  • Clarified that a column GRANT adds privileges; reading only those columns also requires no broader existing rights.
  • Clarified that a view names itself in sqlite_schema.tbl_name; an index names its indexed table.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.