



















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




















































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.
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.
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.
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.
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.
Redundancy = the same piece of data stored in more than one place.
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
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.
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:
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.
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)
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:
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.
Definition: Normalization is the step-by-step process of organizing tables to:
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.
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)
Rules:
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:
Rules:
Note: 2NF only matters when your primary key is composite (two or more columns). 📚 Table: Violates 2NF: Enrollment(StudentID, CourseID, StudentName, CourseName, Grade)
3NF vs BCNF difference:
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:
When to use BCNF vs 3NF:
Original ProductID, (^) (bad) ProductName, table: Qty)Orders(CustomerID, CustomerName, CustomerCity, OrderID,
FDs:
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:
Denormalization = intentionally adding redundancy back for performance. When to denormalize:
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
DCL Data Control La nguage
Control permiss ions
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.
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.
A for domain data integrity = the set of allowed values for a column. Choosing the right type is critical.
Why data types matter:
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.
DDL defines and changes structure , not data.
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:
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:
Deletes the entire table — structure AND data. Cannot be undone (usually). sql DROP TABLE Students; ⚠ Warning: DROP is permanent. Always back up first.
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? ✅ ✅
sql
⚠️ Without WHERE, you delete EVERY row. Similar to TRUNCATE, but DELETE is logged row-by-row and can be rolled back.
DCL controls who can do what in the database.
Gives privileges to users. sql GRANT GRANT SELECTALL PRIVILEGES, INSERT ONON StudentsSchoolDB (^) .*TO TOali_user admin_user; ;
Takes privileges away. sql REVOKE INSERT ON Students FROM ali_user; Why DCL matters:
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
Unit 5 zooms in on consistency and accuracy DML and DDL in action while inserting, updating, and deleting., with a strong emphasis on data
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 ;
When inserting, the DB enforces:
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