SEN2104 · Week 1 · Introduction to Database Management Systems

Introduction to database management systems

Why a DBMS is used instead of a file system, schema vs instance, the three-schema architecture, data independence, DDL/DML and the idea of a transaction. The university database we use all semester is introduced here too.

databaseDBMSfile-processing systemdata redundancydata modelschemainstancethree-schema architecturephysical data independencelogical data independenceDDLDMLtransactionACIDdatabase administrator (DBA)

The database course starts with an introductory week in which you learn the language of the rest of the semester. In the exam this week usually shows up as definition, classification and “which one?” questions: schema or instance, physical or logical independence, DDL or DML, which letter of ACID. They are short questions, but it is easy to lose points on them. Five things to keep in mind:

  1. A DBMS = data + the collection of programs that access that data. The goal is to keep data both easy to use and safe.
  2. The schema is the design, the instance is the data right now. The schema rarely changes, the instance changes constantly.
  3. Three levels: external, logical, physical. The independence between them comes in two kinds.
  4. DDL changes the structure, DML changes the data.
  5. A transaction either happens completely or not at all. ACID describes this with four properties.

The database we use all semester

In every week we use the same small university database. That way the ER diagram, relational algebra, SQL and normalization are all discussed on the same tables, and you can check the result of every query by hand. There are six tables:

  • department(dept_name, building, budget)
  • instructor(inst_id, name, dept_name, salary)
  • student(stu_id, name, dept_name, tot_cred)
  • course(course_id, title, dept_name, credits)
  • teaches(inst_id, course_id)
  • takes(stu_id, course_id, grade)

This week we only need to look at the student table:

stu_idnamedept_nametot_cred
S1AdaCS60
S2BoraCS30
S3CemEE45
S4DefneMATH90
S5EceCS15
S6FiratEE0
S7GizemNULL10

Gizem’s department is not known yet, so it is NULL. This row will be very useful in the SQL weeks.

Why a DBMS instead of a file system?

Before databases became common, organizations kept their data in operating system files. Each department wrote its own file and its own program. This is called a file-processing system. These are the problems of that approach that you are expected to list in the exam:

ProblemUniversity example
Data redundancy and inconsistencyBora’s department is in both the registrar’s file and the department’s file. One gets updated to EE, the other stays CS.
Difficulty in accessing dataWhen a new question like “students with more than 40 credits” comes up, a new program has to be written.
Data isolationThe data is scattered over different files in different formats. Combining it is hard.
Integrity problemsThe rule “course credits must be between 1 and 6” is buried inside every program. Adding a new rule means changing all the programs.
Atomicity problemIf the power goes out in the middle of a money transfer, money leaves one account and never reaches the other.
Concurrent-access anomaliesIf two people take the last seat at the same time, both get registered.
SecurityAccounting should not see a student’s grades. Files have no fine-grained permissions.

A DBMS gives a central solution to each of these problems. For example, integrity constraints are written once in the schema, and the DBMS checks them at every insertion:

INSERT INTO course VALUES ('CS999', 'Test', 'CS', 9);     -- credits must be 1..6
INSERT INTO student VALUES ('S9', 'Ilke', 'PHYS', 0);    -- there is no PHYS department
INSERT INTO student VALUES ('S1', 'Kopya', 'CS', 0);     -- S1 already exists
CHECK constraint failed: credits BETWEEN 1 AND 6
FOREIGN KEY constraint failed
UNIQUE constraint failed: student.stu_id

All three statements were rejected. No application program had to write these checks.

Data models

A data model is a collection of concepts used to describe data, the relationships between data, their meaning and constraints. The ones you will meet in this course:

  • Relational model: Data is kept in tables (relations). Today it is the most common model and the center of the course. Details in week 3.
  • Entity-relationship model (ER): A model used in the design phase that thinks in terms of entities and the relationships between them. Week 2.
  • Object-based model: Brings ideas such as inheritance and encapsulation from object-oriented programming to data.
  • Semi-structured model: Records of the same kind may have different fields. JSON and XML are examples.
  • Historically there were also the network and hierarchical models, which are rare today.

Schema and instance

An analogy from programming: the schema is like the type definition of a variable, and the instance is like the current value of that variable.

  • student(stu_id, name, dept_name, tot_cred) is a schema. Column names, types, keys, constraints.
  • The 7-row table above is the current instance.

When you add a row, the instance changes and the schema stays the same. In the verification run, the row count went from 7 to 8 after the INSERT, and the column count stayed at 4. Changing the schema requires a DDL command such as ALTER TABLE, and that is done rarely.

PITFALL · “schema” is used in two senses. Sometimes it means the structure of a single table (relation schema), sometimes the design of the whole database (database schema). Work it out from the context in the exam. In both cases the opposite term is “instance”.

Three-schema architecture and data independence

To protect the user from details, a DBMS describes data at three levels of abstraction:

   external (view) level     advisor screen   |  accounting screen   |  ...
              |                 (each user group sees a part of the data)
   logical (conceptual) level   all tables, columns, relationships, constraints
              |
   physical (internal) level    files, blocks, indexes, record layout
  • Physical level: How is the data stored on disk? A heap file or a sorted file? Which column has a B+ tree?
  • Logical level: What data exists and how is it related? The student, course and takes tables and their constraints. The DBA and the designer work at this level.
  • External (view) level: The part a particular user sees. For example, an advisor sees only a student’s name and department, not the grades.

Thanks to the mappings between levels, a change at one level does not break the level above it. This is called data independence.

KindWhat changes?Who is protected?Example
Physical data independencethe physical schemathe logical schema and the applicationsadding an index on tot_cred
Logical data independencethe logical schemathe external schemas (views) and the applicationssplitting the student table in two and defining a view with the old name

We actually ran both examples. Before the index was added, the SQLite query plan scanned the whole table; afterwards it used the index, but the result rows stayed the same:

SELECT name FROM student WHERE tot_cred > 40
plan before: SCAN student
plan after : SEARCH student USING INDEX idx_cred (tot_cred>?)
result (in both cases): Ada, Cem, Defne

For logical independence, the student table was split into student_core and student_credit, and then a view named student was defined that joins the two. The old query, without any change, gave the same result:

CREATE VIEW student AS
  SELECT c.stu_id, c.name, c.dept_name, k.tot_cred
  FROM student_core c JOIN student_credit k USING (stu_id);

SELECT name FROM student WHERE dept_name = 'CS';
Ada
Bora
Ece

PITFALL · which one is harder? Achieving logical data independence is harder than achieving physical independence. Applications depend directly on table and column names. If you drop a column, no view can bring it back.

Database languages: DDL and DML

SQL is one language, but its commands fall into two groups:

GroupJobCommands
DDL (data definition language)defines and changes the schemaCREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, CREATE VIEW
DML (data manipulation language)queries and changes the dataSELECT, INSERT, UPDATE, DELETE

The output of DDL is stored in the data dictionary. This is a special collection of tables that holds “data about data” (metadata). The DBMS looks there before every query.

DML can be of two styles. In procedural DML, you tell the system step by step “how to find the data”. In declarative DML, you say only “what you want”, and the DBMS decides how to find it. SQL is declarative:

SELECT stu_id, name FROM student WHERE tot_cred > 40;
S1 | Ada
S3 | Cem
S4 | Defne

In this query we did not say which index to use or in what order to read the rows. The query processor chose that. Weeks 12 and 13 explain exactly how that choice is made.

Transactions and ACID

A transaction is a sequence of operations that counts logically as a single unit of work. The classic example is a money transfer: take from A, add to B. Both must happen together. The DBMS makes four promises for each transaction:

LetterPropertyMeaning
AAtomicityEither all steps happen or none. Work left half-done is undone.
CConsistencyA transaction that starts from a consistent state ends in a consistent state.
IIsolationTransactions running at the same time do not see each other’s intermediate state.
DDurabilityA COMMITted change remains after a crash.

We tried atomicity in SQLite. The accounts are A = 500, B = 200 and the constraint is balance >= 0. The transaction first adds 700 to B, then tries to subtract 700 from A:

BEGIN
UPDATE account SET balance = balance + 700 WHERE acc = 'B'   -- succeeded, B = 900
UPDATE account SET balance = balance - 700 WHERE acc = 'A'   -- CHECK error (A would be -200)
ROLLBACK
result: A = 500, B = 200

Although the first UPDATE succeeded, ROLLBACK undid it too. A valid transfer of 300, on the other hand, completed with COMMIT: A = 200, B = 500, and the total of 700 was preserved.

Users and the parts of a DBMS

Four kinds of people talk to a database:

  • Naive user: Uses ready-made interfaces. A student who picks a course on the registration page.
  • Application programmer: Writes those interfaces. Calls SQL from inside a program.
  • Sophisticated user: Writes queries directly or uses analysis tools. A data analyst.
  • Database administrator (DBA): Defines the schema, chooses the physical layout and indexes, grants permissions, takes backups, monitors performance.

Inside the DBMS there are three main parts. The storage manager writes data to and reads it from disk and handles buffer management. The query processor parses the SQL, chooses the cheapest plan and runs it. The transaction manager provides ACID through concurrency control and crash recovery.

Common mistakes

Wrong ideaThe truth
The schema changes often, the instance is fixedThe opposite: the instance changes with every INSERT/UPDATE/DELETE
DELETE is a DDL commandDELETE removes rows and is DML. DROP TABLE removes the table (DDL)
CREATE INDEX is DMLAn index is a structure, so it is DDL
Adding an index is logical data independenceIt is a change at the physical level, so physical independence
Logical independence is easierIt is harder, because applications depend on table and column names
Atomicity and durability are the same thingAtomicity undoes unfinished work, durability preserves finished work
The application checks the integrity rulesThe DBMS checks them itself with the constraints in the schema (CHECK, FK, PK)
SQL is proceduralSQL is declarative: you write what you want, the DBMS chooses how to do it

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1easy

In a database, which one changes frequently over time: the schema or the instance?

Show answer
The instance

The schema is the design of the table: which columns, which types, which constraints. It rarely changes. The instance is the full set of rows at a given moment. Every INSERT, UPDATE and DELETE changes the instance. In the verification run, inserting one row into student raised the row count from 7 to 8, while the column count stayed at 4.

Question 2easy

Classify each statement as DDL or DML: (1) SELECT, (2) ALTER TABLE, (3) DELETE, (4) CREATE INDEX.

Show answer
DML, DDL, DML, DDL

DDL (data definition language) defines structure: CREATE, ALTER, DROP. An index is also a structure, so CREATE INDEX is DDL. DML (data manipulation language) deals with the data itself: SELECT, INSERT, UPDATE, DELETE. Pitfall: DELETE removes rows, not the table. DROP TABLE, which removes the table, is DDL.

Question 3easy

Which of the following is not a typical problem of a file-processing system?

  1. Data redundancy and inconsistency
  2. Difficulty in accessing data
  3. Concurrent-access anomalies
  4. Physical data independence
Show answer
Physical data independence

The first three are the classic troubles of file systems: the same information in several files (redundancy) and inconsistency when one copy is updated; having to write a new program for every new question; data corrupted when two users write at the same time. Physical data independence is not a problem. It is an advantage that a DBMS brings.

Question 4medium

The DBA adds a B+ tree index on student(tot_cred). No application code changes, and every query returns the same rows. Which kind of data independence does this illustrate?

Show answer
Physical data independence

What changed is how the data is stored and found, that is, the physical (internal) level. The logical schema stayed the same and the applications were not affected. In the verification run, the plan of the tot_cred > 40 query was SCAN student before and SEARCH student USING INDEX idx_cred after the index, and the result rows stayed the same.

Question 5medium

The student table is split into student_core(stu_id, name, dept_name) and student_credit(stu_id, tot_cred). A view named student that joins them is created, so old programs keep working. Which kind of data independence is this?

Show answer
Logical data independence

This time the conceptual (logical) schema changed: one table was split into two. The programs at the external level still see the same interface thanks to the view. A change in the conceptual schema that does not break the external schemas is logical data independence. In the verification run, the old query SELECT name FROM student WHERE dept_name = 'CS' returned Ada, Bora, Ece through the view.

Question 6medium

Using the sample student table, write an SQL query that lists the names of students in the CS department, and give the result.

Show answer
SELECT name FROM student WHERE dept_name = 'CS'; → Ada, Bora, Ece

WHERE filters the rows and SELECT picks the requested column. The rows whose dept_name is 'CS' are S1 (Ada), S2 (Bora) and S5 (Ece). S7 Gizem's department is NULL, so the equality test does not return her. The query was run in SQLite.

Question 7easy

How many rows does SELECT * FROM student WHERE tot_cred >= 30; return on the sample data?

Show answer
4

The tot_cred values are: Ada 60, Bora 30, Cem 45, Defne 90, Ece 15, Firat 0, Gizem 10. Those with 30 or more are Ada, Bora, Cem and Defne. Because the operator is >=, Bora (exactly 30) is included. The result is 4 rows.

Question 8medium

The statement INSERT INTO student VALUES ('S9', 'Ilke', 'PHYS', 0); is executed on the sample database. What happens and why?

Show answer
It is rejected: foreign key violation (no PHYS department)

student.dept_name is a foreign key that references the department(dept_name) table. The department table contains only CS, EE, MATH and BIO. Since 'PHYS' is not there, the DBMS rejects the row. This is an example of an integrity constraint being enforced by the DBMS instead of by application code. SQLite raised 'FOREIGN KEY constraint failed'.

Question 9hard

Accounts: A = 500, B = 200, with constraint balance >= 0. A transaction runs B := B + 700 and then A := A - 700; the second update violates the constraint and the transaction is rolled back. What are the final balances, and which ACID property guarantees this?

Show answer
A = 500, B = 200 (Atomicity)

Even though the first UPDATE succeeded, the transaction as a whole could not complete. Atomicity says 'all or nothing': ROLLBACK undoes the first update too. The balances stay at their starting values, 500 and 200. This was tried exactly in SQLite with BEGIN, two UPDATEs, a CHECK error and ROLLBACK.

Question 10medium

A transaction commits, and one second later the server loses power. After restart, the committed changes are still there. Which ACID property is this?

Show answer
Durability

Durability: a COMMITted change is not lost even if the system crashes. The DBMS provides this with a log file and a recovery mechanism. Do not confuse it with atomicity: atomicity undoes work that was left half-done, while durability preserves work that was completed.

Question 11hard

In the three-schema architecture, at which level is each described? (a) records of student are stored in a heap file with a B+ tree on stu_id; (b) an advisor's screen shows only name and dept_name of students.

Show answer
(a) internal (physical) level, (b) external (view) level

(a) The file organization and the index describe how data is kept on disk: the internal (physical) level. (b) A view that shows one group of users a part of the data is the external (view) level. In between is the conceptual (logical) level: all tables, columns and constraints.

Question 12easy

Which user type writes no SQL and interacts with the database only through forms such as a course registration web page?

  1. Database administrator
  2. Application programmer
  3. Sophisticated user
  4. Naive user
Show answer
Naive user

The naive (end) user works through a ready-made interface, like a student who clicks a button on the course registration page. The application programmer writes the code of that page, the sophisticated user (analyst) writes queries directly, and the DBA manages the schema, permissions and physical layout.

Verification: All SQL examples and answers were run with node:sqlite (SQLite 3.53): verify/SEN2104/01.mjs. Constraint violations (CHECK, FK, PK), atomicity with ROLLBACK, logical data independence with a view, and the changed query plan after an index (EXPLAIN QUERY PLAN) were all actually tried.

Review card

DBMS = data + the programs that access that data. Gains over a file system: less redundancy/inconsistency, easy access, integrity constraints, atomicity, concurrent access, security. SCHEMA = design (rarely changes) INSTANCE = the rows right now (changes constantly) 3 levels: external (view) → logical (conceptual) → physical (internal) Physical independence: index/file layout changes, the logical schema and the application stay the same Logical independence: the logical schema changes (splitting a table), views protect the application (harder) DDL: CREATE ALTER DROP (an index is DDL too) DML: SELECT INSERT UPDATE DELETE DELETE removes rows (DML), DROP removes a table (DDL) Data models: relational, ER, object-based, semi-structured (JSON/XML) ACID: Atomicity (all or nothing), Consistency, Isolation, Durability (a commit is permanent) Users: naive, application programmer, sophisticated, DBA DBMS parts: storage manager, query processor, transaction manager