Courses / Databases for Backend Interviews / Chapter 3
Module 2 · Database foundations · Chapter 3 of 27
Databases and the DBMS: Catalogues, Schemas and Data Independence
Builds on Before Databases: What Goes Wrong with Plain Files. Next up: Data Modelling: From Requirements to Conceptual, Logical and Physical Models.
Part 1 · Database, DBMS and the database approach
Three terms that are often mixed up
Every shop app, bank and booking site keeps its facts in one place that several programs can trust at the same time. That place, and the software that runs it, each have a precise name.
Data is the recorded facts: an item named "Notebook" that costs 45 rupees. A database is an organised collection of related data kept for a purpose, such as everything a stationery shop knows about its stock. A database management system, or DBMS, is the software that stores the database and answers requests for it. PostgreSQL, MySQL and SQLite are DBMSs.
A database system is the whole set: the DBMS, the database, and the programs that use them. People often say "database" for all three, and in daily talk that is fine. When you read documentation, the difference matters: you install a DBMS, and you create a database inside it.
The previous chapter listed what goes wrong when each program handles its own files. The database approach answers that by keeping one shared, self-describing collection of data, and moving the common jobs into the DBMS.
The jobs a DBMS takes over
Think of the DBMS as a service that every program calls instead of opening files itself. It takes on a fixed set of jobs.
| Job | What the DBMS does | File problem it removes |
|---|---|---|
| Storage | Lays data out on disk and reads only the parts needed | Every program parses the whole file |
| Queries | Accepts a question in a language, SQL, and works out how to answer it | A new function for each question |
| Integrity | Checks rules such as NOT NULL, CHECK and foreign keys | Each writer must remember the rules |
| Concurrency | Lets many sessions work at once without lost updates | Two writers overwrite each other |
| Recovery | Restores a consistent state after a crash | Torn files |
| Security | Controls who may read or change what | Anyone with the file sees everything |
Four more traits come with the approach. The data describes itself, which the next lesson shows. Programs are independent of the storage layout, so a table can be reorganised without rewriting them. Different users can have different views of the same data. And one copy of each fact can be shared, with controlled redundancy instead of accidental copies.
A first database in a few lines
This script creates a table of stationery items, inserts three rows and asks two questions. It uses PGlite (version 0.5.15 here, which reports PostgreSQL 18.6), a build of PostgreSQL that runs inside a Node process, so you need only npm install @electric-sql/pglite. Results are printed with a short helper that lays rows out as an aligned text table.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE items ( item_id int PRIMARY KEY, name text NOT NULL, price numeric(8,2) NOT NULL, stock int NOT NULL )`) await db.exec(` INSERT INTO items (item_id, name, price, stock) VALUES (1, 'Notebook', 45.00, 120), (2, 'Gel pen', 10.00, 300), (3, 'Geometry box', 85.50, 40)`) const cheap = await db.query( 'SELECT name, price FROM items WHERE price < 50 ORDER BY price') show(cheap.rows) const worth = await db.query( 'SELECT sum(price * stock) AS stock_value FROM items') show(worth.rows)
try { await db.query( `INSERT INTO items (item_id, name, price, stock) VALUES ($1, $2, $3, $4)`, [1, 'Eraser', 5, 200]) } catch (e) { const err = e as { code: string; detail: string } console.log(`refused: ${err.code} ${err.detail}`) }
name | price ---------+------ Gel pen | 10.00 Notebook | 45.00 (2 rows) stock_value ----------- 11820.00 (1 row) refused: 23505 Key (item_id)=(1) already exists.
Neither question needed a loop in your code. You described what you wanted, and the DBMS found the rows. The second query computes a value from two columns across all rows, which a file would have needed a custom function for.
SQL of this kind is called declarative: you state the result you want, not the steps to get it. The code in the previous chapter was procedural: it said read each line, parse it, compare it, add it up. With a declarative language the DBMS is free to choose the steps, and to choose different steps when the data grows.
The last statement tried to add an eraser with item id 1, which the notebook already has. The DBMS refused it with SQLSTATE 23505 and a detail naming the key. The primary key was declared once, in CREATE TABLE, and now every program that writes to items gets the same check. That is the duplicate-order problem of the previous chapter solved by the DBMS instead of by each writer.
Check yourself
What is the difference between a database and a DBMS?
- The database is the stored collection of data. The DBMS is the software that stores it and answers requests.
- You install a DBMS and create databases inside it.
A second program inserts an item whose item_id already exists. What stops it, and what does the program see?
- The primary key declared in CREATE TABLE. The DBMS checks it on every write, whichever program sends the row.
- The insert fails with SQLSTATE 23505, unique violation, and a detail naming the key, as in the run.
What does it mean that programs are independent of the storage layout?
- A table can be reorganised on disk, for example by adding an index, without changing the programs that query it.
- The next lessons show this in a run.
Part 2 · Data that describes itself
The catalogue
A JSON Lines file does not say what its fields are. You learn the structure from the code that reads it. A database stores the structure inside itself.
The system catalogue is a set of tables, maintained by the DBMS, that describe everything in the database: tables, columns, types, constraints, indexes and users. When you run CREATE TABLE, the DBMS writes rows into the catalogue. When you ask what columns a table has, it reads them from there. The catalogue is also called metadata, which means data about data.
PostgreSQL offers two ways to read the catalogue. The information schema is a set of views defined by the SQL standard, so the queries are largely portable across systems that implement it. The system catalogues in pg_catalog are PostgreSQL's own tables. They show more, including indexes and internal details, and their shape can change between versions.
Reading the catalogue with queries
The script builds two small tables with a primary key, a unique constraint, a check and a foreign key, then asks the catalogue about them.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE items ( item_id int PRIMARY KEY, name text NOT NULL, price numeric(8,2) NOT NULL CHECK (price > 0), stock int NOT NULL DEFAULT 0 ); CREATE TABLE suppliers ( supplier_id int PRIMARY KEY, name text NOT NULL UNIQUE ); ALTER TABLE items ADD COLUMN supplier_id int REFERENCES suppliers (supplier_id); `)
console.log('-- information_schema.columns') show((await db.query(` SELECT table_name, column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' ORDER BY table_name, ordinal_position`)).rows) console.log('-- information_schema.table_constraints') show((await db.query(` SELECT table_name, constraint_name, constraint_type FROM information_schema.table_constraints WHERE table_schema = 'public' AND constraint_type <> 'CHECK' ORDER BY table_name, constraint_name`)).rows) console.log('-- pg_catalog: the same tables as the engine stores them') show((await db.query(` SELECT c.relname, c.relkind, c.relnatts AS columns FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' ORDER BY c.relname`)).rows)
-- information_schema.columns table_name | column_name | data_type | is_nullable -----------+-------------+-----------+------------ items | item_id | integer | NO items | name | text | NO items | price | numeric | NO items | stock | integer | NO items | supplier_id | integer | YES suppliers | supplier_id | integer | NO suppliers | name | text | NO (7 rows) -- information_schema.table_constraints table_name | constraint_name | constraint_type -----------+------------------------+---------------- items | items_pkey | PRIMARY KEY items | items_supplier_id_fkey | FOREIGN KEY suppliers | suppliers_name_key | UNIQUE suppliers | suppliers_pkey | PRIMARY KEY (4 rows) -- pg_catalog: the same tables as the engine stores them relname | relkind | columns -------------------+---------+-------- items | r | 5 items_pkey | i | 1 suppliers | r | 2 suppliers_name_key | i | 1 suppliers_pkey | i | 1 (5 rows)
The first result lists every column with its type and whether it allows NULL. The second lists the keys and unique constraints, including the names PostgreSQL chose when you gave none: items_pkey, suppliers_name_key. The check constraint is left out here by the filter. The third query reads pg_class, where the letter r marks an ordinary table and i an index. The indexes items_pkey and suppliers_name_key were created for you to enforce the keys, so the catalogue shows five rows where you made only two tables.
Why the catalogue matters
Tools read the catalogue. A database browser lists your tables from it. An object-relational mapper checks column names against it. A migration tool compares it with your code. Because every DBMS exposes its structure through queries, the same tools can work on any database. Even the \d items command of psql, PostgreSQL's command-line client, is a shortcut that runs catalogue queries like the ones above and formats the answer.
The DBMS itself uses the catalogue on every statement. When you write SELECT name FROM items, the parser looks items up in the catalogue to find the table and check that the column name exists. That is why a misspelt column is caught at once, before any row is read.
One consequence is easy to miss: changing the structure is just another change to data. ALTER TABLE updates catalogue rows and, if needed, rewrites table data. In PostgreSQL most such statements can run inside a transaction, a group of changes that takes effect all together or not at all. The script below adds a column inside a transaction, looks at the catalogue, and rolls the change back.
import { PGlite } from '@electric-sql/pglite' const db = new PGlite() await db.exec('CREATE TABLE items (item_id int PRIMARY KEY, name text)') const columns = async () => { const r = await db.query<{ column_name: string }>(` SELECT column_name FROM information_schema.columns WHERE table_name = 'items' ORDER BY ordinal_position`) return r.rows.map((row) => row.column_name).join(', ') } // A schema change is a change to catalog rows, so it can be undone. await db.exec('BEGIN') await db.exec('ALTER TABLE items ADD COLUMN colour text') console.log(`inside the transaction: ${await columns()}`) await db.exec('ROLLBACK') console.log(`after ROLLBACK: ${await columns()}`) // The parser checks names against the catalog before reading a row. try { await db.query('SELECT nme FROM items') } catch (e) { const err = e as { code: string; message: string } console.log(`misspelt column: ${err.code} ${err.message}`) }
inside the transaction: item_id, name, colour after ROLLBACK: item_id, name misspelt column: 42703 column "nme" does not exist
Inside the transaction the catalogue already listed colour. After ROLLBACK it was gone, as if the statement had never run. Not every command can be undone this way: the PostgreSQL reference pages for CREATE DATABASE and CREATE INDEX CONCURRENTLY say they cannot run inside a transaction block. The misspelt column nme was refused with SQLSTATE 42703 before any row was read, because the name was not in the catalogue. Transactions get a full treatment in a later chapter.
Part 3 · Three schemas and data independence
Three levels of description
A schema is a description of the structure of data. A widely used way to organise a database is to describe it at three levels, called the three-schema architecture.
| Level | Describes | In PostgreSQL | Who cares |
|---|---|---|---|
| External | What one group of users sees | Views, and the columns a role may read | Application users, report writers |
| Conceptual | All the data, its keys and rules | Tables, columns, constraints | Database designers, developers |
| Internal | How the data is stored | Pages, indexes, tablespaces | The DBMS, administrators |
DescribesWhat one group of users sees
In PostgreSQLViews, and the columns a role may read
Who caresApplication users, report writers
DescribesAll the data, its keys and rules
In PostgreSQLTables, columns, constraints
Who caresDatabase designers, developers
Changing the layout under a query
The script fills a table with 5,000 items, asks for one item by name, then adds an index and a new column and asks the same question again. It also creates a view that hides the cost column.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE items ( item_id int PRIMARY KEY, name text NOT NULL, price numeric(8,2) NOT NULL, cost numeric(8,2) NOT NULL ); INSERT INTO items (item_id, name, price, cost) SELECT n, 'Item ' || n, 20 + n % 80, 10 + n % 40 FROM generate_series(1, 5000) AS n; ANALYZE items; `) const q = `SELECT item_id, price FROM items WHERE name = 'Item 4242'` const plan = async () => { const r = await db.query(`EXPLAIN (COSTS OFF) ${q}`) return r.rows.map((row) => row['QUERY PLAN']).join('\n') } console.log('-- the query') show((await db.query(q)).rows) console.log('-- plan before') console.log(await plan())
await db.exec('CREATE INDEX items_name_idx ON items (name)') await db.exec('ALTER TABLE items ADD COLUMN shelf text') console.log('-- same query after an index and a new column') show((await db.query(q)).rows) console.log('-- plan after') console.log(await plan()) // External level: a view for the shop counter that hides the cost. await db.exec(` CREATE VIEW counter_items AS SELECT item_id, name, price FROM items`) console.log('-- what the counter staff see') show((await db.query( 'SELECT * FROM counter_items WHERE item_id = 7')).rows) console.log('-- what the table holds') show((await db.query('SELECT * FROM items WHERE item_id = 7')).rows) // The limit: a column that a view uses cannot simply disappear. try { await db.exec('ALTER TABLE items DROP COLUMN price') } catch (e) { const err = e as { code: string; message: string } const [what, why] = err.message.split(' because ') console.log(`drop price: ${err.code} ${what}`) console.log(` because ${why}`) }
-- the query item_id | price --------+------ 4242 | 22.00 (1 row) -- plan before Seq Scan on items Filter: (name = 'Item 4242'::text) -- same query after an index and a new column item_id | price --------+------ 4242 | 22.00 (1 row) -- plan after Index Scan using items_name_idx on items Index Cond: (name = 'Item 4242'::text) -- what the counter staff see item_id | name | price --------+--------+------ 7 | Item 7 | 27.00 (1 row) -- what the table holds item_id | name | price | cost | shelf --------+--------+-------+-------+------ 7 | Item 7 | 27.00 | 17.00 | NULL (1 row) drop price: 2BP01 cannot drop column price of table items because other objects depend on it
Reading the result
The query text did not change, and neither did its answer. The plan did change. Before the index, the engine scanned the whole table and filtered it. After the index, it used the index to go straight to the matching row. That is physical independence: the internal level changed, the query did not.
The new column shelf appears in SELECT * on the table, as NULL for existing rows, but the query that named its columns was not touched. That is logical independence for the case of adding a column. It also shows a common mistake: application code that uses SELECT * gets one more field after the change, and code that reads fields by position, or copies rows into a fixed structure, can break. Naming the columns you need keeps a query stable.
The view counter_items is an external schema. The counter staff see three columns. The table holds five. A view is a stored query that you use like a table. Because the DBMS expands the view into its query when it runs, there is no second copy of the data to keep in step. The next lesson shows the step where that happens.
The last statement shows the limit. Dropping price was refused with SQLSTATE 2BP01, because the view counter_items depends on it. PostgreSQL records that dependency in its catalogue, so it will not silently break the external level. You would have to change or drop the view first, and the people who use it would notice.
A teammate wants to drop a column that a view uses. What did PostgreSQL do in the run, and why is that the safe behaviour?
- It refused the drop with SQLSTATE 2BP01 because the view depends on the column.
- Dropping it would break the external schema that users of the view rely on, so the view must be changed first, on purpose.
In the run, what changed when the index was added and what stayed the same?
- The plan changed from Seq Scan to Index Scan.
- The query text and its result stayed the same.
Part 4 · Inside the DBMS
From SQL text to rows
When an application sends a statement, it passes through fixed stages. The PostgreSQL documentation on the path of a query names them.
| Stage | What it does |
|---|---|
| Connection | The application connects, sends the query text and waits for the result |
| Parser | Checks the syntax and builds a query tree; names are looked up in the catalogue |
| Rewrite system | Applies rules from the catalogue to the tree; this is where a view is replaced by its base query |
| Planner | Considers different ways to get the same result, estimates the cost of each and keeps the cheapest plan |
| Executor | Walks the plan tree, fetching rows, sorting and joining as the plan says, and returns the result |
The planner is what lets you write SQL without saying how. You say which rows you want, and it chooses between scanning a table and using an index. The executor then asks the storage layer for pages.
The buffer cache and the log
Data lives on disk in fixed-size blocks called pages, 8 KB each in PostgreSQL by default. The executor does not read the disk directly. It asks the buffer manager, which keeps recently used pages in a region of memory called the buffer cache. In PostgreSQL this is the shared buffers. A page found there is a hit. A page that must be requested from the operating system is a read. The operating system keeps its own file cache, so a read may still be answered from memory, but it is outside the DBMS's cache and costs more.
Changes follow a different rule. Before a modified page may be written to its data file, a record describing the change is written to the write-ahead log, or WAL, and flushed. After a crash the DBMS replays the log to restore a consistent state. This is the answer to the torn files of the previous chapter. A later chapter explains it in full.
Watch for where the second run stops: it never leaves the buffer cache
Read it as steps
The first run asks for 896 pages outside the cache, the second finds them all in the buffer cache.
The scene draws what the next page measures: the same query run twice.
Counting hits and reads
To see the cache you need a server whose cache you can empty. This script starts a real PostgreSQL server from the embedded-postgres package (18.6.0-beta.19 here: the beta label belongs to the package, and the server inside is the PostgreSQL 18.6 release), creates a table of 2,00,000 rows, stops the server, which throws its cache away, and starts it again. Then it runs the same query twice under EXPLAIN (ANALYZE, BUFFERS), which runs the query and reports the pages it touched. In PostgreSQL 18, EXPLAIN ANALYZE reports buffers even when you leave BUFFERS out; the script names it anyway so the intent is clear.
import EmbeddedPostgres from 'embedded-postgres' import pg from 'pg' import { rmSync } from 'node:fs' const port = 56300 const dir = './pgdata-c2' rmSync(dir, { recursive: true, force: true }) function makeServer() { return new EmbeddedPostgres({ databaseDir: dir, port, user: 'postgres', password: 'pw', persistent: true, onLog: () => {}, }) } async function connect() { const c = new pg.Client({ host: '127.0.0.1', port, user: 'postgres', password: 'pw', database: 'postgres' }) await c.connect() return c } async function plan(c: pg.Client, sql: string) { const opts = 'ANALYZE, BUFFERS, COSTS OFF, TIMING OFF' const r = await c.query(`EXPLAIN (${opts}) ${sql}`) for (const row of r.rows) console.log(row['QUERY PLAN']) }
const sql = 'SELECT count(*) FROM stock WHERE qty > 50' let server = makeServer() await server.initialise() await server.start() let c = await connect() await c.query(` CREATE TABLE stock AS SELECT n AS item_id, n % 100 AS qty FROM generate_series(1, 200000) AS n`) await c.query('CHECKPOINT') await c.end() await server.stop() // shared memory is gone with the server server = makeServer() await server.start() c = await connect() console.log('-- first run after a restart') await plan(c, sql) console.log('-- second run') await plan(c, sql) await c.end() await server.stop() rmSync(dir, { recursive: true, force: true })
-- first run after a restart Aggregate (actual rows=1.00 loops=1) Buffers: shared read=896 dirtied=885 -> Seq Scan on stock (actual rows=98000.00 loops=1) Filter: (qty > 50) Rows Removed by Filter: 102000 Buffers: shared read=896 dirtied=885 Planning: Buffers: shared hit=18 read=9 Planning Time: 0.815 ms Execution Time: 69.730 ms -- second run Aggregate (actual rows=1.00 loops=1) Buffers: shared hit=896 -> Seq Scan on stock (actual rows=98000.00 loops=1) Filter: (qty > 50) Rows Removed by Filter: 102000 Buffers: shared hit=896 Planning Time: 0.067 ms Execution Time: 9.494 ms
Timings vary from run to run on this machine.
Part 5 · Users, roles and when a database is overkill
Who may do what
Once many programs and people share one database, you need to control access. A role in PostgreSQL is a named set of privileges. A role that can log in plays the part of a user. Others are used as groups, and you can give one role to another.
A privilege is permission to do one kind of thing to one object: SELECT, INSERT, UPDATE, DELETE and a few more. GRANT gives a privilege and REVOKE takes it back. A privilege can be given on a whole table or on selected columns. The DBA, the database administrator, is the person or role that creates roles and sets these rules, along with backups and upgrades. Application code normally connects as a role that has only the privileges it needs, not as the superuser.
The rule behind this is least privilege: give a role only the access its job needs. If the password of an application role leaks, the damage is limited to what that role could do, and a bug in the application cannot drop a table it has no right to touch.
This is the external level from earlier in practice. The counter staff role gets to see names and ids. It never sees the cost.
A role that is denied
The script creates a role counter_staff and grants it SELECT on two columns. Then SET ROLE makes the session act as that role, and each statement is attempted in turn.
import { PGlite } from '@electric-sql/pglite' import { show } from '../show.ts' const db = new PGlite() await db.exec(` CREATE TABLE items (item_id int PRIMARY KEY, name text, cost numeric); INSERT INTO items (item_id, name, cost) VALUES (1, 'Notebook', 31.50), (2, 'Gel pen', 6.25); CREATE ROLE counter_staff; GRANT SELECT (item_id, name) ON items TO counter_staff; `) async function attempt(sql: string) { try { const r = await db.query(sql) console.log(`ok: ${sql}`) show(r.rows) } catch (e) { const err = e as { code: string; message: string } console.log(`denied: ${sql}`) console.log(` ${err.code} ${err.message}`) } } await db.exec('SET ROLE counter_staff') await attempt('SELECT item_id, name FROM items') await attempt('SELECT cost FROM items') await attempt('DELETE FROM items') await db.exec('RESET ROLE') await attempt('SELECT current_user')
ok: SELECT item_id, name FROM items item_id | name --------+--------- 1 | Notebook 2 | Gel pen (2 rows) denied: SELECT cost FROM items 42501 permission denied for table items denied: DELETE FROM items 42501 permission denied for table items ok: SELECT current_user current_user ------------ postgres (1 row)
The first query used only the granted columns and worked. Reading cost was refused with SQLSTATE 42501, the standard code for insufficient privilege, and so was DELETE. The message names the table and not the column in both cases. After RESET ROLE the session is back to the owner.
When a database is overkill
A DBMS adds a process or a library, a schema to maintain and a new way to fail. It earns that cost when data is shared, questions vary or rules matter. Some jobs do not need it.
| Situation | A file or a simpler tool may be enough |
|---|---|
| Application logs | An append-only file, read by a log tool |
| Settings for one program | A JSON or text config file |
| Data that is written once and read in full | A CSV or Parquet export |
| One program, a few thousand records, no sharing | An in-process store, which may itself be an embedded database such as SQLite |
Note the last row: an embedded DBMS runs inside your program, with no separate server. You still get queries, constraints and transactions. The choice is rarely "file or database" in the end. It is how much of the database approach you need.
If a project starts as a file and later outgrows it, the move is not a loss. The records, their fields and their rules carry over into tables. The design work in the next chapters is the same either way.
| Term | Meaning |
|---|---|
| DBMS | Software that stores a database and answers requests for it |
| System catalogue | Tables kept by the DBMS that describe the database itself |
| Data independence | Changing one level of the schema without breaking the level above |
| Buffer cache |
All chapters · Previous: Before Databases: What Goes Wrong with Plain Files