Docsity

COMPLETE DATABASE MANAGEMENT SYSTEM NOTES 2, Study notes of Distributed Database Management Systems

Toggle sidebar
bg1
📚 THE ULTIMATE COMPLETE DATABASE
MANAGEMENT SYSTEMS STUDY GUIDE
Units 3–8: From Theory to Practice — Everything You
Need to Know (Expanded Edition)
How to use this document:Read it top-to-bottom once for the full
picture. Each unit builds on the previous ones. Every concept has multiple
analogies, definitions, examples, step-by-step walkthroughs,
common mistakes, and "why it matters" notes. Nothing is skipped.
This is the only document you need. If a concept feels hard, re-read the
analogy — it's designed to make it click.
A note on depth:This guide intentionally over-explains. It assumes you
know nothing and builds up. If you already know a section, skim it. If you
don't, read every word. The goal is that after reading this, you could teach
the material to someone else.
MASTER ROADMAP — How Everything Fits
Together
text
UNIT 3: DESIGN → How should a good database look? (theory)
UNIT 4: LANGUAGE → What is SQL and its parts? (vocabulary)
UNIT 5: ACTION → How do I safely change data? (DML/DDL in
practice)
UNIT 6: QUERYING → How do I combine data from many tables?
(joins, views, subqueries)
UNIT 7: TRANSACTIONS → How do I handle concurrency & connect apps?
(ACID, JDBC/ODBC)
UNIT 8: LIFECYCLE → How do I build, maintain, and evolve a
database? (SDLC, Waterfall)
The flow: Design cleanly → speak correctly → operate safely → query powerfully
→ handle concurrency → manage the whole lifecycle.
Why this order matters:You can't query well (Unit 6) if your tables are badly
designed (Unit 3). You can't modify data safely (Unit 5) if you don't know SQL's parts
(Unit 4). You can't handle concurrency (Unit 7) if you don't understand transactions.
And you can't maintain a database (Unit 8) if you don't understand everything that
came before. Each unit is a brick in the wall.
📚 PART 1 — UNIT 3: Relational Database Design
1. Why Does Database Design Even Matter?
Imagine a school keeps ALL its info in ONE giant spreadsheet:
Student Course Instructor Instructor Dept
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b

Partial preview of the text

Download COMPLETE DATABASE MANAGEMENT SYSTEM NOTES 2 and more Study notes Distributed Database Management Systems in PDF only on Docsity!

📚 THE ULTIMATE COMPLETE DATABASE

MANAGEMENT SYSTEMS STUDY GUIDE

Units 3–8: From Theory to Practice — Everything You

Need to Know (Expanded Edition)

How to use this document: Read it top-to-bottom once for the full picture. Each unit builds on the previous ones. Every concept has analogies, definitions, examples, step-by-step walkthroughs, multiple common mistakes, and "why it matters" notes. Nothing is skipped. This is the only document you need. If a concept feels hard, re-read the analogy — it's designed to make it click. A note on depth: know nothing and builds up. If you already know a section, skim it. If youThis guide intentionally over-explains. It assumes you don't, read every word. The goal is that after reading this, you could teach the material to someone else.

 MASTER ROADMAP — How Everything Fits

Together

text UNIT UNIT 3:4: DESIGNLANGUAGE →→ HowWhat should is SQL a andgood its database parts? look?(vocabulary) (theory) UNIT practice) 5: ACTION → How do I safely change data? (DML/DDL in UNIT (joins, 6: QUERYINGviews, subqueries) → How do I combine data from many tables? UNIT (ACID, 7: JDBC/ODBC)TRANSACTIONS → How do I handle concurrency & connect apps? UNIT database? 8: LIFECYCLE (SDLC, Waterfall)→ How do I build, maintain, and evolve a

The flow: → handle concurrency Design cleanly → → manage the whole lifecycle speak correctly → operate safely. → query powerfully

Why this order matters: designed (Unit 3). You can't modify data safely (Unit 5) if you don't know SQL's partsYou can't query well (Unit 6) if your tables are badly (Unit 4). You can't handle concurrency (Unit 7) if you don't understand transactions. And you can't maintain a database (Unit 8) if you don't understand everything that came before. Each unit is a brick in the wall.

📚 PART 1 — UNIT 3: Relational Database Design

1. Why Does Database Design Even Matter?

Imagine a school keeps ALL its info in ONE giant spreadsheet: Student Course Instructor Instructor Dept

Phone Ali DB101 Dr. Smith 555-1234 CS Sara DB101 Dr. Smith 555-1234 CS Ali CS102 Dr. Jones 555-9999 CS Omar DB101 Dr. Smith 555-1234 CS This looks fine until reality hits. Let's walk through what actually happens: Scenario 1: Dr. Smith changes her phone number. You must update every single row she appears in. In our tiny example, that's 3 rows. But in a real university with 50,000 students, Dr. Smith might appear in 10,000 rows. You update 9,999 of them and miss one. Now the database says her phone is both 555- 1234 AND 555-5678. unreliable. Which is correct? Nobody knows. The data has become

Scenario 2: You hire a new instructor, Dr. Lee. You want to add Dr. Lee to the database. But wait — the table only has columns for Student, Course, Instructor, Instructor Phone, and Dept. Dr. Lee doesn't have a student yet. So you can't add her without inventing a fake student. The database forces you to enter bad data just to record a simple fact.

Scenario 3: Sara drops CS102. You delete Sara's row for CS102. But Dr. Jones only teaches CS102, and Sara was the only student in it. By deleting Sara's row, you've accidentally deleted the only record that Dr. Jones exists that anymore.. She's still employed, but the database doesn't know

This is a bad design. Unit 3 is entirely about fixing this. The solution is called normalization , and it's built on the concept of functional dependencies. The core insight: to change Dr. Smith's phone number, you change it in one row, and every query thatIn a good database, each fact lives in exactly one place. If you want needs it automatically sees the new value. If you want to add Dr. Lee, you add her to an Instructors table without needing a student. If Sara drops a course, Dr. Jones remains untouched.

2. Anomalies in Databases

An structured. The word comes from the Greek "anomalia," meaning "irregularity." In anomaly = a problem that occurs because data is stored redundantly or poorly databases, anomalies are irregularities that cause incorrect or inconsistent data. There are three classic types , and you must know all three for exams and real-world work.

📚 A. Insertion Anomaly

Definition: You cannot insert a fact without also inserting unrelated facts. Why instructors) into one structure. To insert one entity, you're forced to provide data for it happens: The table combines multiple entities (students, courses, the others. Example: 555-0000) unless you also assign them a student and course. The databaseIn the table above, you cannot add a new instructor (say Dr. Lee, phone forces you to invent fake data or skip the insert entirely. Real-world analogy: Imagine a form that requires you to write a customer's order before you're allowed to write their name in the phonebook. You want to add "John

📚 Memory trick: Think of anomalies as "I.D.U." — I nsertion, D eletion, U pdate. If you can remember "I.D.U.," you can remember all three.

3. Redundant Information

Redundancy = the same piece of data stored in more than one place.

3.1 Types of Redundancy

Type What it means Harm Example Controlled red undancy Intentional duplication (e.g., foreign keys) for performance

Mostly safe if ma naged Storing DeptID in Students table

Uncontrolled r edundancy

Accidental duplication (e.g., storing Dept name in every student row)

Causes anomalie s, wastes storag e

Storing "Computer Science" in 500 student rows

3.2 Why Redundancy Is Bad — The Full List

  1. Wasted space 17 characters, that's 170,000 characters wasted.— the same string stored 10,000 times. If "Computer Science" is
  2. Update anomalies — every copy must be changed. Miss one → inconsistency.
  3. Inconsistency things. — copies drift apart over time. Different rows say different
  4. Insertion anomalies — can't add one fact without another.
  5. Deletion anomalies — deleting one fact destroys another.
  6. Slower queries — more data to scan.
  7. Harder maintenance — more places to check when something changes.

3.3 Why Some Redundancy Is OK

  • Foreign keys duplicate a reference, not the content. Storing DeptID = 1 in a student row is fine — it's just a pointer. Storing not fine — it's the actual content. DeptName = "Computer Science" is
  • Denormalization warehouses do this. Example: storing the total order count on a customer row to— sometimes we intentionally add redundancy for speed. Data avoid counting orders every time. This is a trade-off: faster reads, but must be kept in sync.
  • Caching — storing computed results to avoid recomputation. The rule: when it's accidentalRedundancy is OK when it's and unmanaged. controlled, intentional, and managed. It's bad

4. Functional Dependency (FD)

This normalization becomes easy. If you don't understand FDs, you can't understand is the single most important concept in Unit 3. Master this and normalization.

4.1 The Definition

X → Y (read: "X functionally determines Y") means: if two rows have the same value for X, they MUST have the same value for Y. X is called the determinant , Y is called the dependent. In plain English: Y. There's no ambiguity.X is like a key that unlocks Y. If you know X, you automatically know

Real-world examples:

  • StudentID → StudentName — if two rows have the same StudentID, they must have the same name. ✅ (A student has one name.)
  • StudentName → StudentID — FALSE , because two students can share a name (John Smith ×2). Knowing the name doesn't tell you the ID.
  • SocialSecurityNumber → Name, BirthDate — SSN uniquely identifies a person. ✅
  • ZipCode is a partial → City FD — a good example of why you must verify FDs with real data. — mostly true, but not always (some zip codes span cities). So this
  • CourseID → CourseName, Credits — a course has one name and one credit count. ✅ Analogy: snack. SoThink of a vending machine. Press button B4 → Snack. But Snack → B4 is false: two different buttons can both give you B4 → you always get the same the same candy. The button determines the snack, but the snack doesn't determine the button.

Another analogy: A function in math. f(x) = x². If you know x, you know f(x). But if you know f(x) = 4, x could be 2 or -2. So x → f(x) but not f(x) → x. Same idea.

4.2 Types of Functional Dependencies — Complete List

Type Definition Example Good or Bad? Trivial FD Y is a subset of X. Always true, no info.

{StudentID, e} → StudentID Nam Neutral

Non-trivial FD Y is NOT a subset of X.^ StudentID^ →^ Name^ Depends Completely no n-trivial X ∩ Y = ∅. StudentID^ →^ Name^ Depends Full FD Y depends on ALL of X, not part of it.

{StudentID, CourseID} → Grade (need both)

Good

Partial FD Y depends on only PART of a composite X.

{StudentID, CourseID} → StudentName (only needs StudentID)

⚠️ BAD

Transitive FD X → Y and Y → Z, therefore X → Z.^ StudentID ID → DeptName^ →^ Dept ⚠️ BAD Multivalued FD X →→ Y: for one X, multiple Y values

Student Course (a student →→ takes many courses)

Used in 4NF

FDs:

  • StudentID → StudentName, DeptID
  • DeptID → DeptName
  • CourseID → CourseName
  • {StudentID, CourseID} → Grade Analysis:
  • Candidate key = {StudentID, CourseID} (need both to determine Grade).
  • Partial dependencies: StudentID → StudentName, DeptID (only needs part of key). ⚠️
  • Partial dependencies: CourseID → CourseName. ⚠️
  • Transitive dependency: StudentID → DeptID → DeptName. ⚠️ Conclusion: This table violates 2NF and 3NF. Needs normalization.

4.6 Full FD vs Partial FD — A Clear Distinction

  • Full FD: to find the grade.{StudentID, Neither alone is enough. CourseID} → Grade. You need BOTH StudentID and CourseID ✅
  • Partial FD: the name. CourseID is irrelevant.{StudentID, CourseID} (^) ⚠️→ StudentName. You only need StudentID to find

Exam tip: Partial dependencies only exist when the primary key is composite (two or more columns). If the PK is a single column, there can be no partial dependencies.

5. Normalization

Definition: Normalization is the step-by-step process of organizing tables to:

  • ✅ Remove redundancy
  • ✅ Eliminate anomalies
  • ✅ Preserve data integrity Each "step" is called a design. Normal Form (NF). Higher NF = stricter rules = cleaner

Analogy: categories (1NF). Then you put each category in its own box (2NF). Then you label theNormalization is like organizing a messy closet. First you sort items into boxes correctly (3NF). Then you make sure no box contains something that belongs in another box (BCNF). By the end, everything has a place, and you can find anything instantly. Important denormalize (^) caveat: for performance. But you should normalize first, then denormalize only ifNormalization is not always the end goal. Sometimes you needed.

📚 The Normal Forms — Quick Map

text Unnormalized ↓ Data 1NF (^) ↓ (atomic values) 2NF (^) ↓ (no partial dependencies) 3NF (^) ↓ (no transitive dependencies) BCNF (^) ↓ (every determinant is a candidate key)

4NF, 5NF ... (beyond this course)

5.1 First Normal Form (1NF)

Rules:

  1. Every column holds atomic (indivisible) values.
  2. No repeating groups or multi-value columns.
  3. Each row is unique (a primary key exists). 📚 Violates 1NF: StudentID Name Courses 1 Ali DB101, CS102, MATH2 01

The "Courses" column holds a easily. list — not atomic. You can't query "who is in DB101?"

📚 Fixed (1NF): StudentID Name Course 1 Ali DB 1 Ali CS 1 Ali MATH Now each cell has one value. You can query "who is in DB101?" with a simple WHERE clause. Analogy: 1NF says "one cell = one fact." No Swiss-army-knife cells. Common 1NF violations:

  • Storing multiple phone numbers in one column: "555-1234, 555-5678".
  • Storing an array: ["red", "green", "blue"].
  • Repeating columns: Phone1, Phone2, Phone3. How to fix:
  • Multi-value column: Create a new row for each value.
  • Repeating columns: Create a new table with one row per value.
  • Array: Same as multi-value column.

5.2 Second Normal Form (2NF)

Rules:

  1. Must already be in 1NF.
  2. No partial dependencies primary key, not part of it.— every non-key column must depend on the entire

Note: 2NF only matters when your primary key is composite (two or more columns). 📚 Table: Violates 2NF: Enrollment(StudentID, CourseID, StudentName, CourseName, Grade)

  • Primary key = {StudentID, CourseID}
  • StudentID → StudentName ← partial (only needs part of key!)
  • CourseID → CourseName ← partial

3NF vs BCNF difference:

  • 3NF allows a non-key determinant IF the dependent is a prime attribute (part of a candidate key).
  • BCNF allows no exceptions — every determinant must be a superkey. In simpler terms:
  • 3NF: the key.""Every non-key column depends on the key, the whole key, and nothing but (Allows some exceptions.)
  • BCNF: "Every determinant must be a candidate key." (No exceptions.) Classic BCNF Violation Example: Table: Teaching(Student, Course, Instructor)
  • Rule: Each instructor teaches exactly ONE course. (But a course can have multiple instructors.)
  • FDs: ◦ {Student, Course} → Instructor (a student in a course has one instructor) ◦ Instructor → Course (an instructor teaches one course)
  • Candidate keys: {Student, Course} and {Student, Instructor}.
  • But → violates BCNF Instructor → Course (though it satisfies 3NF, since Course is prime). has a determinant ( Instructor ) that is NOT a superkey

Why it's a problem: "Dr. Smith teaches DB101" is stored 30 times.If Dr. Smith teaches DB101, and 30 students take DB101, then Redundancy!

📚 BCNF Decomposition:

  • Teaches(Instructor, Course)
  • Enrolled(Student, Instructor) Now every determinant is a superkey. ✔ Why BCNF matters: It eliminates all redundancy caused by FDs. It's the gold standard for OLTP systems. ⚠️ can't always check all original FDs on the decomposed tables). 3NF  Trade-off: BCNF decomposition can sometimes lose a dependency (you guarantees dependency preservation but may allow tiny redundancy. That's why both exist.

When to use BCNF vs 3NF:

  • BCNF: When eliminating all redundancy is critical (most OLTP systems).
  • 3NF: When preserving all dependencies is critical (some data warehouses).

5.5 Beyond BCNF — 4NF and 5NF (Brief Mention)

  • 4NF: Deals with multivalued dependencies. Eliminates redundancy caused by independent multi-valued facts.
  • 5NF: scenarios.Deals with join dependencies. Eliminates redundancy in complex join
  • 6NF: Extreme normalization for temporal databases. These are beyond this course, but good to know they exist.

6. Worked Example — From Bad to BCNF (Step-by-Step)

Original ProductID, (^) (bad) ProductName, table: Qty)Orders(CustomerID, CustomerName, CustomerCity, OrderID,

FDs:

  • CustomerID → CustomerName, CustomerCity
  • OrderID → CustomerID
  • ProductID → ProductName
  • {OrderID, ProductID} → Qty Step-by-step normalization: Step Action Result Unnormalized Original table Orders(CustomerID, CustomerName, CustomerCity, ProductID, ProductName, OrderID, Qty) 1NF Ensure no multi-valued cells (Qty is atomic — OK).

Same table.

2NF Remove partial deps: ProductName depends only on ProductID.

OrderLine(OrderID, ProductID, Product(ProductID, Qty) + ProductName) Order(OrderID, + CustomerID, CustomerName, CustomerCity) 3NF Remove transitive: CustomerName, CustomerCity depend on CustomerID (not OrderID).

Customer(CustomerID, CustomerName, CustomerCity) Order(OrderID, + CustomerID) OrderLine(OrderID, + ProductID, Product(ProductID, Qty) + ProductName) BCNF Check every determinant. All are candidate keys. ✅

Same as 3NF result.

Final schema:

  • Customer(CustomerID, CustomerName, CustomerCity)
  • Order(OrderID, CustomerID)
  • OrderLine(OrderID, ProductID, Qty)
  • Product(ProductID, ProductName) Result: combine data.Every fact lives once. No anomalies. Updates are safe. Queries use joins to

7. Denormalization — When to Break the Rules

Denormalization = intentionally adding redundancy back for performance. When to denormalize:

What SQL can do:

  • Define structures (tables, columns, keys)
  • Manipulate data (insert, read, update, delete)
  • Control access (who can do what)
  • Manage transactions (commit or undo)
  • Create views (virtual tables)
  • Set constraints (rules for data)

2. Advantages of SQL

  1. Standardized — Same basic syntax across all major RDBMS. Learn once, use ev erywhere.
  2. Declarative write loops.) Example:— You say SELECT what you want, not * FROM Students how WHERE to get it. (Unlike Java where you Age > 21 — you don't say "loop through rows, check age, add to result." The DB engine figures that out.
  3. Non-procedural — The DB engine figures out the best path (query optimizer).
  4. Portable — Learn once, use everywhere.
  5. Powerful — One query can join 10 tables and aggregate millions of rows.
  6. Secure — Fine-grained permission control (DCL).
  7. Interactive & embedded — Use from a console OR inside an app (Java, Python, etc.).
  8. Backed by ACID transactions — reliability guarantees.
  9. Widely supported — Every major DB and many tools support SQL.
  10. Expressive — Complex queries can be written in a few lines.

3. Parts of SQL (The "Family Tree")

SQL is divided into sublanguages , each with a different job: Sublanguage Full Name Purpose Commands DDL Data Definition L anguage Define/modify ructure st CREATE, ALTER, DROP, TRUNCATE, RENAME DML Data Manipulati on Language Work with data inside tables

SELECT, INSER T, UPDATE, DEL

ETE

DCL Data Control La nguage

Control permiss ions

GRANT, REVOK

E

TCL Transaction Con trol Language Manage tions transac COMMIT, ROLL BACK, SAVEPOI NT Mnemonic:D efine → M anipulate → C ontrol → T ransact. Analogy: Think of a library.

  • DDL = building the shelves and rooms (structure).
  • DML = putting books on shelves and taking them off (data).
  • DCL = deciding who has a library card and what they can borrow (permissions).
  • TCL = managing a borrowing transaction (all-or-nothing).

DDL vs DML vs DCL — The Core Difference

Feature DDL DML DCL Acts on Table structure Table rows/data Users & privile ges Rollback possibl e? Usually o-commit) NO (aut YES ctions)(with transa Usually NO Frequency Occasional Constant Occasional Example CREATE^ TABLE^ INSERT^ INTO^ GRANT^ SELECT Who uses it? DBAs, developer s Developers, apps DBAs, security

Why the distinction matters: schema. DML changes are transactional and can be rolled back. Understanding theDDL changes are usually permanent and affect the difference helps you avoid accidental data loss.

4. Domain Types in SQL (Data Types)

A for domain data integrity = the set of allowed values for a column. Choosing the right type is critical.

Why data types matter:

  • They enforce what kind of data can be stored.
  • They determine how much space is used.
  • They affect query performance.
  • They prevent invalid data from entering. Category Type Description Example When to us e Character CHAR(n)^ Fixed-length string ate codes CHAR(2) for st When all values are the same length VARCHAR(n) (^) Variable-len gth string

VARCHAR(100) for names^ When length s vary TEXT (^) Long text Blog posts When length is unknown Numeric INT / INTEGER Whole numb ers Age, quantit y When decimals aren't needed SMALLINT INT , BIG Smaller/larg er ints IDs When range matters

/^ DECIMAL(p,s) NUMERIC^ Exact decim als^ Money ( MAL(10,2)DECI)^ When precisi on matters FLOAT, REAL, D Approximate Scientific dat When

PK in another table (creates relationships) Candidate Key Any column(s) that could serve as PK

StudentID, Email Composite Key PK made of 2+ column s

{StudentID, CourseID} Superkey Any set of columns that uniquely identifies a row (superset of a candidate key)

{StudentID, Name}

Null Unknown/missing value — NOT the same as 0 or ""

NULL

Schema The overall structure/blueprint of a database

SchoolDB

View A virtual table based on a query

CS_Students Index A lookup structure that speeds up queries

idx_name

Why terminology matters: Exams often use formal terms (relation, tuple, attribute) while real life uses informal terms (table, row, column). You need to know both.

6. DDL — Data Definition Language

DDL defines and changes structure , not data.

6.1 CREATE

sql CREATE StudentID TABLE Students INT PRIMARY ( KEY, Name Age VARCHARINT CHECK( 50 )( (^) AgeNOT >=NULL 0 ),, Email DeptID VARCHARINT, ( 100 ) UNIQUE, );^ FOREIGN^ KEY^ (DeptID)^ REFERENCES^ Departments(DeptID) What's happening:

  • PRIMARY KEY — unique, not null.
  • NOT NULL — must have a value.
  • CHECK — enforce a rule (Age can't be negative).
  • UNIQUE — no duplicates (Email).
  • FOREIGN KEY — link to another table. Other CREATE variants:
  • CREATE DATABASE SchoolDB;
  • CREATE INDEX idx_name ON Students(Name);
  • CREATE VIEW CS_Students AS SELECT * FROM Students WHERE DeptID = 1; Common mistakes:
  • Forgetting NOT NULL on required columns.
  • Using VARCHAR(255) for everything.
  • Not adding a primary key.
  • Forgetting foreign key constraints.

6.2 ALTER

Changes an existing table's structure. sql ALTER ALTER TABLETABLE StudentsStudents ADDMODIFY COLUMN Age PhoneINT NOT VARCHAR NULL;( 15 ); ALTER ALTER TABLETABLE StudentsStudents DROPRENAME COLUMN COLUMN Phone Name; TO FullName;

Why ALTER is tricky:

  • Some changes lock the table (blocking reads/writes).
  • Some changes can't be undone.
  • Some changes require rewriting all data.

6.3 DROP

Deletes the entire table — structure AND data. Cannot be undone (usually). sql DROP TABLE Students; ⚠ Warning: DROP is permanent. Always back up first.

6.4 TRUNCATE

Removes all rows but keeps the table structure. sql TRUNCATE TABLE Students; DROP vs TRUNCATE: DROP TRUNCATE Removes Structure + data Only data Rollback ✅ Usually ✅ Speed Fast Very fast Can re-use table? No (must recreate) Yes Triggers fire? ✅ ✅

6.5 RENAME

sql

⚠️  Without WHERE, you delete EVERY row. Similar to TRUNCATE, but DELETE is logged row-by-row and can be rolled back.

8. DCL — Data Control Language

DCL controls who can do what in the database.

8.1 GRANT

Gives privileges to users. sql GRANT GRANT SELECTALL PRIVILEGES, INSERT ONON StudentsSchoolDB (^) .*TO TOali_user admin_user; ;

8.2 REVOKE

Takes privileges away. sql REVOKE INSERT ON Students FROM ali_user; Why DCL matters:

  • Least privilege principle — give users only what they need.
  • Prevents accidental or malicious data destruction.
  • Essential for compliance (HIPAA, GDPR, SOX).
  • Auditing: track who did what.

9. Unit 4 — Key Takeaways

Topic Key point SQL Standard language for relational DBs DDL Structure: CREATE, ALTER, DROP, TRUNCATE DML Data: SELECT, INSERT, UPDATE, DELETE DCL Permissions: GRANT, REVOKE TCL Transactions: COMMIT, ROLLBACK Data types Enforce integrity through domain constraints Terminology Relation=table, Tuple=row, Attribute=column

⚙ PART 3 — UNIT 5: Applying SQL to Modify Data

Safely

Unit 5 zooms in on consistency and accuracy DML and DDL in action while inserting, updating, and deleting., with a strong emphasis on data

1. INSERT — Adding Data

1.1 Syntax Options

Full form (recommended): sql INSERT VALUES INTO( 10 , Students'Layla', ( 20 StudentID, 2 ); , Name, Age, DeptID)

Short form (fragile — depends on column order): sql INSERT INTO Students VALUES ( 10 , 'Layla', 20 , 2 ); Why full form is better: breaks (wrong number of values).If someone adds a column to the table, the short form The full form is explicit and safe.

Multi-row: sql INSERT ( 11 , INTO'Hassan' Students, 21 , ( 1 StudentID), , Name, Age, DeptID) VALUES ( 12 , 'Mona', 22 , 3 ); INSERT from a SELECT (bulk copy): sql INSERT SELECT INTO* FROM Students_Backup Students WHERE DeptID = 1 ;

1.2 Integrity Rules to Respect

When inserting, the DB enforces:

  • Primary key uniqueness — can't insert duplicate IDs.
  • NOT NULL — can't skip required columns.
  • FOREIGN KEY — referenced row must exist.
  • CHECK — value must satisfy the rule.
  • UNIQUE — no duplicates in unique columns.
  • Data type match — 'abc' can't go into an INT column.

1.3 Common Mistakes

Mistake Consequence How to avoid Forgetting a NOT NULL column Insert fails List all columns explici tly Using a value that violates FK Insert fails Check parent table firs t Inserting wrong data ty Implicit conversion or Match types carefully