DBMS concepts, SQL queries, normalization और transactions – Detailed notes in English and हिंदी
SELECT s.name, c.title FROM Students s JOIN Enrollments e ON s.id = e.student_id JOIN Courses c ON c.id = e.course_id WHERE s.id = 42;
| Type | Description | Example |
|---|---|---|
| Hierarchical DBMS | Tree-like (parent-child). One parent per child. | IBM IMS |
| Network DBMS | Graph-like; a child can have multiple parents. | IDMS |
| Relational DBMS (RDBMS) | Data stored in tables (relations); SQL-based. | MySQL, Oracle, PostgreSQL |
| Object-Oriented DBMS | Stores objects directly. | db4o, ObjectDB |
| NoSQL DBMS | Document, key-value, column, graph stores. | MongoDB, Redis, Cassandra, Neo4j |
| NewSQL | SQL + scalability of NoSQL. | CockroachDB, Google Spanner |
Users / Applications
─────────────────────────────
External Level → Views (View 1, View 2, ...)
─────────────────────────────
Conceptual Level → Logical Schema (Tables, Constraints)
─────────────────────────────
Internal Level → Physical Schema (Files, Indexes)
─────────────────────────────
Storage / Disk
─────────────────────────────
Mappings:
External → Conceptual (View mapping)
Conceptual → Internal (Storage mapping)
SELECT s.name, c.title FROM Students s JOIN Enrollments e ON s.id = e.student_id JOIN Courses c ON c.id = e.course_id WHERE s.id = 42;
| प्रकार | विवरण | उदाहरण |
|---|---|---|
| Hierarchical DBMS | Tree जैसा (parent-child)। हर child का एक parent। | IBM IMS |
| Network DBMS | Graph जैसा; child के कई parents हो सकते हैं। | IDMS |
| Relational DBMS (RDBMS) | Tables (relations) में data; SQL-based। | MySQL, Oracle, PostgreSQL |
| Object-Oriented DBMS | Objects सीधे store होते हैं। | db4o, ObjectDB |
| NoSQL DBMS | Document, key-value, column, graph stores। | MongoDB, Redis, Cassandra, Neo4j |
| NewSQL | SQL + NoSQL की scalability। | CockroachDB, Google Spanner |
Users / Applications
─────────────────────────────
External Level → Views (View 1, View 2, ...)
─────────────────────────────
Conceptual Level → Logical Schema (Tables, Constraints)
─────────────────────────────
Internal Level → Physical Schema (Files, Indexes)
─────────────────────────────
Storage / Disk
─────────────────────────────
Mappings:
External → Conceptual (View mapping)
Conceptual → Internal (Storage mapping)
Client (Web Browser / Mobile App)
│ HTTP
▼
Application Server (Business Logic)
│ SQL / Driver
▼
DBMS Server (MySQL / PostgreSQL)
│ Reads/Writes
▼
Physical Storage (Disks, Files)
Users never talk to the DBMS directly; the application layer enforces business rules and
the DBMS enforces data integrity.
A. DBMS Architectures:
| Architecture | Description | Use Case |
|---|---|---|
| 1-Tier | Client, application, and DBMS on same machine. | Learning, single-user desktop apps. |
| 2-Tier | Client talks directly to DBMS over network. | LAN apps with trusted clients. |
| 3-Tier | Client → App Server → DBMS. | Web apps, enterprise systems. |
| N-Tier | More layers: cache, queue, microservices. | Large-scale distributed apps. |
B. Data Models:
| Model | Description |
|---|---|
| Hierarchical | Tree structure, one parent per record. |
| Network | Graph, a record can have many parents. |
| Relational | Tables with rows and columns; SQL-based. |
| Object-Oriented | Objects, classes, inheritance. |
| Document (NoSQL) | JSON/BSON documents; nested. |
| Graph (NoSQL) | Nodes and edges with properties. |
┌────────────────────────────────────┐
│ Query Processor │
│ Parser → Optimizer → Executor │
└─────────────┬──────────────────────┘
│
┌─────────────▼──────────────────────┐
│ Transaction Manager │
│ Concurrency Control + Recovery │
└─────────────┬──────────────────────┘
│
┌─────────────▼──────────────────────┐
│ Storage Manager │
│ Buffer Manager + File Manager │
└─────────────┬──────────────────────┘
│
┌─────────────▼──────────────────────┐
│ Physical Storage │
│ (Disks, Files, Indexes) │
└────────────────────────────────────┘
Client (Web Browser / Mobile App)
│ HTTP
▼
Application Server (Business Logic)
│ SQL / Driver
▼
DBMS Server (MySQL / PostgreSQL)
│ Reads/Writes
▼
Physical Storage (Disks, Files)
Users DBMS से सीधे बात नहीं करते; application layer business rules enforce करता है और
DBMS data integrity।
A. DBMS Architectures:
| Architecture | विवरण | Use Case |
|---|---|---|
| 1-Tier | Client, application और DBMS एक ही machine पर। | Learning, single-user desktop apps। |
| 2-Tier | Client सीधे DBMS से network पर बात करता है। | LAN apps with trusted clients। |
| 3-Tier | Client → App Server → DBMS। | Web apps, enterprise systems। |
| N-Tier | और layers: cache, queue, microservices। | Large-scale distributed apps। |
B. Data Models:
| Model | विवरण |
|---|---|
| Hierarchical | Tree structure, हर record का एक parent। |
| Network | Graph, एक record के कई parents हो सकते हैं। |
| Relational | Tables with rows और columns; SQL-based। |
| Object-Oriented | Objects, classes, inheritance। |
| Document (NoSQL) | JSON/BSON documents; nested। |
| Graph (NoSQL) | Nodes और edges with properties। |
┌────────────────────────────────────┐
│ Query Processor │
│ Parser → Optimizer → Executor │
└─────────────┬──────────────────────┘
│
┌─────────────▼──────────────────────┐
│ Transaction Manager │
│ Concurrency Control + Recovery │
└─────────────┬──────────────────────┘
│
┌─────────────▼──────────────────────┐
│ Storage Manager │
│ Buffer Manager + File Manager │
└─────────────┬──────────────────────┘
│
┌─────────────▼──────────────────────┐
│ Physical Storage │
│ (Disks, Files, Indexes) │
└────────────────────────────────────┘
┌────────────┐ enrolls ┌────────────┐
│ Student │◄──────────────►│ Course │
└────────────┘ (M:N) └────────────┘
│ id │ code
│ name │ title
│ dob │ credits
▲
│ teaches (1:N)
│
┌──────────────┐
│ Instructor │
└──────────────┘
id, name, dept
A. Concepts in ER Model:
| Concept | Symbol | Meaning |
|---|---|---|
| Entity | Rectangle | A thing (Student, Course). |
| Weak entity | Double rectangle | Entity with no key of its own (Dependent of Employee). |
| Attribute | Ellipse | Property (name, age). |
| Key attribute | Underlined ellipse | Primary identifier (id). |
| Multivalued attribute | Double ellipse | Phone numbers (list). |
| Derived attribute | Dashed ellipse | Age (derived from dob). |
| Composite attribute | Ellipse with sub-ellipses | Name = first + last. |
| Relationship | Diamond | Enrolls-in, teaches. |
B. Cardinalities:
| Cardinality | Meaning | Example |
|---|---|---|
| 1:1 | One-to-one | Person ↔ Passport |
| 1:N | One-to-many | Instructor → Courses |
| M:N | Many-to-many | Student ↔ Course |
C. Participation constraints: Total vs partial; existence dependency.
Entity ┌───────────┐
│ Student │
└───────────┘
Weak Entity ╔═══════════╗
║ Dependent ║
╚═══════════╝
Attribute ( name )
Key Attribute ( id ) ← underlined
Multivalued (( phones ))
Derived ( age ) ← dashed
Relationship ◇ enrolls ◇
Cardinality (1:N) ─── 1 ───◇─── N ───
┌────────────┐ enrolls ┌────────────┐
│ Student │◄──────────────►│ Course │
└────────────┘ (M:N) └────────────┘
│ id │ code
│ name │ title
│ dob │ credits
▲
│ teaches (1:N)
│
┌──────────────┐
│ Instructor │
└──────────────┘
id, name, dept
A. ER Model के concepts:
| Concept | Symbol | मतलब |
|---|---|---|
| Entity | Rectangle | एक चीज़ (Student, Course)। |
| Weak entity | Double rectangle | अपनी key नहीं (Employee का Dependent)। |
| Attribute | Ellipse | गुण (name, age)। |
| Key attribute | Underlined ellipse | Primary identifier (id)। |
| Multivalued attribute | Double ellipse | Phone numbers (list)। |
| Derived attribute | Dashed ellipse | Age (dob से derived)। |
| Composite attribute | Ellipse with sub-ellipses | Name = first + last। |
| Relationship | Diamond | Enrolls-in, teaches। |
B. Cardinalities:
| Cardinality | मतलब | उदाहरण |
|---|---|---|
| 1:1 | One-to-one | Person ↔ Passport |
| 1:N | One-to-many | Instructor → Courses |
| M:N | Many-to-many | Student ↔ Course |
C. Participation constraints: Total बनाम partial; existence dependency।
Entity ┌───────────┐
│ Student │
└───────────┘
Weak Entity ╔═══════════╗
║ Dependent ║
╚═══════════╝
Attribute ( name )
Key Attribute ( id ) ← underlined
Multivalued (( phones ))
Derived ( age ) ← dashed
Relationship ◇ enrolls ◇
Cardinality (1:N) ─── 1 ───◇─── N ───
Student ( student_id PK, name, email, dept_id FK )
Department ( dept_id PK, dept_name )
Enrollment ( student_id FK, course_id FK, grade,
PRIMARY KEY (student_id, course_id) )
Sample row:
Student(101, 'Amit', 'a@x.com', 3)
└─ student_id is the primary key
└─ dept_id refers to Department(dept_id)
A. Types of Keys:
| Key | Description | Example |
|---|---|---|
| Super key | Any set of attributes that uniquely identifies a tuple. | {student_id, email} |
| Candidate key | Minimal super key. | {student_id} or {email} |
| Primary key (PK) | Chosen candidate key; unique + not null. | student_id |
| Alternate key | Candidate keys not chosen as PK. | |
| Foreign key (FK) | Attribute(s) referring to a PK in another table. | dept_id in Student |
| Composite key | Key made of two or more attributes. | (student_id, course_id) |
| Surrogate key | System-generated identifier. | Auto-increment id |
B. Relational Integrity Constraints:
| Constraint | Rule |
|---|---|
| Domain constraint | Column values must belong to the declared domain. |
| Entity integrity | Primary key cannot be null. |
| Referential integrity | Foreign key must match an existing PK or be null. |
| Key constraint | Primary key must be unique. |
Department Student
┌──────────┬──────────────┐ ┌─────────┬────────┬───────────┬──────────┐
│ dept_id │ dept_name │◄─────│ dept_id │ FK │ │ │
│ (PK) │ │ │ student_id (PK) │ name │ email │
└──────────┴──────────────┘ └─────────┴────────┴───────────┴──────────┘
│
│ FK student_id
▼
Enrollment
┌───────────┬───────────┬────────┐
│ student_id│ course_id │ grade │
│ (PK part) │ (PK part) │ │
└───────────┴───────────┴────────┘
Legend:
PK = Primary key
FK = Foreign key (enforces referential integrity)
Student ( student_id PK, name, email, dept_id FK )
Department ( dept_id PK, dept_name )
Enrollment ( student_id FK, course_id FK, grade,
PRIMARY KEY (student_id, course_id) )
Sample row:
Student(101, 'अमित', 'a@x.com', 3)
└─ student_id primary key है
└─ dept_id Department(dept_id) को refer करता है
A. Keys के प्रकार:
| Key | विवरण | उदाहरण |
|---|---|---|
| Super key | ऐसा attributes का set जो tuple को uniquely identify करे। | {student_id, email} |
| Candidate key | Minimal super key। | {student_id} या {email} |
| Primary key (PK) | चुनी हुई candidate key; unique + not null। | student_id |
| Alternate key | वे candidate keys जो PK नहीं चुनी गईं। | |
| Foreign key (FK) | दूसरी table की PK को refer करने वाले attributes। | Student में dept_id |
| Composite key | दो या ज़्यादा attributes से बनी key। | (student_id, course_id) |
| Surrogate key | System-generated identifier। | Auto-increment id |
B. Relational Integrity Constraints:
| Constraint | Rule |
|---|---|
| Domain constraint | Column values घोषित domain की हों। |
| Entity integrity | Primary key null नहीं हो सकती। |
| Referential integrity | Foreign key किसी existing PK से match करे या null हो। |
| Key constraint | Primary key unique होनी चाहिए। |
Department Student
┌──────────┬──────────────┐ ┌─────────┬────────┬───────────┬──────────┐
│ dept_id │ dept_name │◄─────│ dept_id │ FK │ │ │
│ (PK) │ │ │ student_id (PK) │ name │ email │
└──────────┴──────────────┘ └─────────┴────────┴───────────┴──────────┘
│
│ FK student_id
▼
Enrollment
┌───────────┬───────────┬────────┐
│ student_id│ course_id │ grade │
│ (PK part) │ (PK part) │ │
└───────────┴───────────┴────────┘
Legend:
PK = Primary key
FK = Foreign key (referential integrity enforce करता है)
StudentCourse(student_id, name, course_id, course_name, instructor)
Problem: instructor depends on course, not student.
Update instructor for a course → many rows must change.
After 3NF:
Student(student_id PK, name)
Course(course_id PK, course_name, instructor)
Enrollment(student_id FK, course_id FK, PK(student_id, course_id))
| Normal Form | Rule | Removes |
|---|---|---|
| 1NF | All attributes atomic; no repeating groups. | Multivalued attributes. |
| 2NF | 1NF + no partial dependency on composite key. | Partial dependency. |
| 3NF | 2NF + no transitive dependency of non-key on non-key. | Transitive dependency. |
| BCNF | Every determinant is a candidate key. | Remaining redundancy from overlapping candidate keys. |
| 4NF | BCNF + no multivalued dependency. | Independent multivalued facts. |
| 5NF | No join dependency (project-join normal form). | Certain join dependencies. |
Un-normalised Table
│
▼ (remove repeating groups)
1NF
│
▼ (remove partial dependency on composite key)
2NF
│
▼ (remove transitive dependency: non-key → non-key)
3NF
│
▼ (every determinant is a candidate key)
BCNF
│
▼ (remove multivalued dependency)
4NF
│
▼ (remove join dependency)
5NF
StudentCourse(student_id, name, course_id, course_name, instructor)
समस्या: instructor course पर depend करता है, student पर नहीं।
किसी course का instructor update करने पर कई rows बदलनी पड़ेंगी।
3NF के बाद:
Student(student_id PK, name)
Course(course_id PK, course_name, instructor)
Enrollment(student_id FK, course_id FK, PK(student_id, course_id))
| Normal Form | Rule | क्या हटाता है |
|---|---|---|
| 1NF | सभी attributes atomic; repeating groups नहीं। | Multivalued attributes। |
| 2NF | 1NF + composite key पर partial dependency नहीं। | Partial dependency। |
| 3NF | 2NF + non-key का non-key पर transitive dependency नहीं। | Transitive dependency। |
| BCNF | हर determinant एक candidate key हो। | Overlapping candidate keys से बची redundancy। |
| 4NF | BCNF + multivalued dependency नहीं। | Independent multivalued facts। |
| 5NF | Join dependency नहीं (project-join normal form)। | कुछ join dependencies। |
Un-normalised Table
│
▼ (repeating groups हटाएँ)
1NF
│
▼ (composite key पर partial dependency हटाएँ)
2NF
│
▼ (transitive dependency हटाएँ: non-key → non-key)
3NF
│
▼ (हर determinant candidate key हो)
BCNF
│
▼ (multivalued dependency हटाएँ)
4NF
│
▼ (join dependency हटाएँ)
5NF
CREATE, ALTER, DROP, TRUNCATE,
RENAME. DDL changes are typically auto-committed by the DBMS.
-- CREATE TABLE CREATE TABLE Department ( dept_id INT PRIMARY KEY, dept_name VARCHAR(50) NOT NULL UNIQUE ); CREATE TABLE Student ( student_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE, age INT CHECK (age >= 16), dept_id INT, FOREIGN KEY (dept_id) REFERENCES Department(dept_id) ); -- ALTER TABLE ALTER TABLE Student ADD COLUMN phone VARCHAR(15); ALTER TABLE Student MODIFY phone VARCHAR(20); ALTER TABLE Student DROP COLUMN phone; -- TRUNCATE vs DROP TRUNCATE TABLE Student; -- removes all rows, keeps structure DROP TABLE Student; -- removes table and structure
| Command | Purpose | Rollback? |
|---|---|---|
| CREATE | Create table, view, index, schema, database. | Implicit commit. |
| ALTER | Add/modify/drop columns, constraints. | Implicit commit. |
| DROP | Delete object and structure. | Implicit commit. |
| TRUNCATE | Delete all rows, keep structure; faster than DELETE. | Implicit commit. |
| RENAME | Rename table or column. | Implicit commit. |
Common column types and constraints:
INT, VARCHAR, CHAR,
TEXT, DATE, TIMESTAMP, DECIMAL,
BOOLEAN.PRIMARY KEY, FOREIGN KEY,
UNIQUE, NOT NULL, CHECK,
DEFAULT.TRUNCATE removes all rows efficiently.DROP, TRUNCATE cannot be
rolled back easily.ALTER on huge tables can lock long.IF EXISTS / IF NOT EXISTS
for safe scripts.
CREATE → table exists (structure defined)
│
▼
ALTER → add / change / drop columns and constraints
│
▼
TRUNCATE → remove all rows (structure remains)
│
▼
DROP → remove table and structure entirely
Dependencies:
Parent (Department) ← referenced by FK
Child (Student) → must DROP first
enrolled_on DATE column.CREATE, ALTER, DROP, TRUNCATE,
RENAME। DDL changes आमतौर पर DBMS auto-commit करता है।
-- CREATE TABLE CREATE TABLE Department ( dept_id INT PRIMARY KEY, dept_name VARCHAR(50) NOT NULL UNIQUE ); CREATE TABLE Student ( student_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE, age INT CHECK (age >= 16), dept_id INT, FOREIGN KEY (dept_id) REFERENCES Department(dept_id) ); -- ALTER TABLE ALTER TABLE Student ADD COLUMN phone VARCHAR(15); ALTER TABLE Student MODIFY phone VARCHAR(20); ALTER TABLE Student DROP COLUMN phone; -- TRUNCATE vs DROP TRUNCATE TABLE Student; -- सभी rows हटीं, structure बनी DROP TABLE Student; -- table और structure दोनों गए
| Command | उद्देश्य | Rollback? |
|---|---|---|
| CREATE | Table, view, index, schema, database बनाएँ। | Implicit commit। |
| ALTER | Columns/constraints जोड़ें, बदलें, हटाएँ। | Implicit commit। |
| DROP | Object और structure delete। | Implicit commit। |
| TRUNCATE | सभी rows delete, structure रहे; DELETE से तेज़। | Implicit commit। |
| RENAME | Table या column का नाम बदलें। | Implicit commit। |
सामान्य column types और constraints:
INT, VARCHAR, CHAR,
TEXT, DATE, TIMESTAMP, DECIMAL,
BOOLEAN।PRIMARY KEY, FOREIGN KEY,
UNIQUE, NOT NULL, CHECK,
DEFAULT।TRUNCATE सभी rows तेज़ी से हटाता है।DROP, TRUNCATE आसानी से rollback
नहीं।ALTER लंबा lock कर सकता है।IF EXISTS /
IF NOT EXISTS।
CREATE → table बनी (structure defined)
│
▼
ALTER → columns और constraints add/change/drop
│
▼
TRUNCATE → सभी rows हटीं (structure रही)
│
▼
DROP → table और structure पूरी तरह गए
Dependencies:
Parent (Department) ← FK से referenced
Child (Student) → पहले DROP
enrolled_on DATE column जोड़ने के लिए ALTER लिखिए।INSERT, UPDATE, DELETE, and MERGE.
DML changes are transactional and can be rolled back before commit.
-- INSERT INSERT INTO Department (dept_id, dept_name) VALUES (1, 'Computer Science'), (2, 'Mathematics'); INSERT INTO Student (student_id, name, email, age, dept_id) VALUES (101, 'Amit', 'a@x.com', 20, 1); -- UPDATE UPDATE Student SET age = age + 1 WHERE dept_id = 1; UPDATE Student SET email = 'amit.new@x.com' WHERE student_id = 101; -- DELETE DELETE FROM Student WHERE student_id = 101; -- Transaction (rollback-safe) BEGIN; UPDATE Student SET age = 99 WHERE student_id = 101; ROLLBACK; -- age will not actually change
| Statement | Purpose | Notes |
|---|---|---|
| INSERT | Add new rows. | Can insert single or multiple rows; can insert from SELECT. |
| UPDATE | Modify existing rows. | Always use a WHERE clause to limit scope. |
| DELETE | Remove rows. | Always use WHERE; TRUNCATE is faster for all rows. |
| MERGE / UPSERT | Insert or update in one statement. | Vendor-specific syntax (MERGE, ON CONFLICT, ON DUPLICATE KEY). |
UPDATE or
DELETE without WHERE affects all rows.
BEGIN
│
▼
INSERT / UPDATE / DELETE
│ (changes visible to this session)
▼
More changes …
│
├── COMMIT → changes permanent, visible to all
│
└── ROLLBACK → changes undone
Referential integrity:
Parent (Department) ── FK ── Child (Student)
DELETE parent → fails (or CASCADE deletes child rows
depending on FK rule)
INSERT, UPDATE, DELETE, MERGE। DML
changes transactional होते हैं और commit से पहले rollback हो सकते हैं।
-- INSERT INSERT INTO Department (dept_id, dept_name) VALUES (1, 'Computer Science'), (2, 'Mathematics'); INSERT INTO Student (student_id, name, email, age, dept_id) VALUES (101, 'अमित', 'a@x.com', 20, 1); -- UPDATE UPDATE Student SET age = age + 1 WHERE dept_id = 1; UPDATE Student SET email = 'amit.new@x.com' WHERE student_id = 101; -- DELETE DELETE FROM Student WHERE student_id = 101; -- Transaction (rollback-safe) BEGIN; UPDATE Student SET age = 99 WHERE student_id = 101; ROLLBACK; -- age असल में नहीं बदलेगी
| Statement | उद्देश्य | Notes |
|---|---|---|
| INSERT | नई rows जोड़ें। | Single/multiple rows; SELECT से भी insert। |
| UPDATE | मौजूदा rows बदलें। | हमेशा WHERE से scope सीमित करें। |
| DELETE | Rows हटाएँ। | हमेशा WHERE; सभी rows के लिए TRUNCATE तेज़। |
| MERGE / UPSERT | एक statement में insert या update। | Vendor-specific syntax (MERGE, ON CONFLICT, ON DUPLICATE KEY)। |
UPDATE या
DELETE सभी rows पर।
BEGIN
│
▼
INSERT / UPDATE / DELETE
│ (changes सिर्फ इस session को दिखते हैं)
▼
और changes …
│
├── COMMIT → changes permanent, सबको दिखते हैं
│
└── ROLLBACK → changes undone
Referential integrity:
Parent (Department) ── FK ── Child (Student)
Parent DELETE → fail (या CASCADE से child rows
delete, FK rule पर निर्भर)
SELECT statement. It supports filtering
(WHERE), sorting (ORDER BY), grouping (GROUP BY),
filtering groups (HAVING), joining tables (JOIN), subqueries,
set operations, and window functions.-- INNER JOIN with aggregate SELECT d.dept_name, COUNT(*) AS students FROM Student s JOIN Department d ON s.dept_id = d.dept_id GROUP BY d.dept_name HAVING COUNT(*) > 5 ORDER BY students DESC; -- Subquery: students above average age SELECT name, age FROM Student WHERE age > (SELECT AVG(age) FROM Student); -- LEFT JOIN: departments with no students SELECT d.dept_name FROM Department d LEFT JOIN Student s ON s.dept_id = d.dept_id WHERE s.student_id IS NULL;
A. Joins:
| Join | Returns |
|---|---|
| INNER JOIN | Only matching rows in both tables. |
| LEFT (OUTER) JOIN | All rows from left + matches from right. |
| RIGHT (OUTER) JOIN | All rows from right + matches from left. |
| FULL OUTER JOIN | All rows from both sides. |
| CROSS JOIN | Cartesian product. |
| SELF JOIN | Table joined with itself. |
B. Other DQL concepts:
COUNT, SUM,
AVG, MIN, MAX.UNION, INTERSECT,
EXCEPT.ROW_NUMBER, RANK,
SUM() OVER.WITH clause for readable queries.= NULL never matches; use
IS NULL.
ORDER BY.
Logical order of execution:
1. FROM / JOIN → build the working set
2. WHERE → filter rows
3. GROUP BY → collapse into groups
4. HAVING → filter groups
5. SELECT → compute output columns
6. DISTINCT → remove duplicates
7. ORDER BY → sort
8. LIMIT / OFFSET → paginate
Note: SELECT comes AFTER GROUP BY logically, even
though we type it near the beginning.
SELECT statement। यह filtering
(WHERE), sorting (ORDER BY), grouping (GROUP BY),
groups filter (HAVING), tables join (JOIN), subqueries, set
operations और window functions support करता है।-- INNER JOIN with aggregate SELECT d.dept_name, COUNT(*) AS students FROM Student s JOIN Department d ON s.dept_id = d.dept_id GROUP BY d.dept_name HAVING COUNT(*) > 5 ORDER BY students DESC; -- Subquery: average age से बड़े students SELECT name, age FROM Student WHERE age > (SELECT AVG(age) FROM Student); -- LEFT JOIN: बिना students वाले departments SELECT d.dept_name FROM Department d LEFT JOIN Student s ON s.dept_id = d.dept_id WHERE s.student_id IS NULL;
A. Joins:
| Join | क्या return करता है |
|---|---|
| INNER JOIN | सिर्फ दोनों tables की matching rows। |
| LEFT (OUTER) JOIN | Left की सभी rows + right की matches। |
| RIGHT (OUTER) JOIN | Right की सभी rows + left की matches। |
| FULL OUTER JOIN | दोनों ओर की सभी rows। |
| CROSS JOIN | Cartesian product। |
| SELF JOIN | Table का खुद से join। |
B. अन्य DQL concepts:
COUNT, SUM,
AVG, MIN, MAX।UNION, INTERSECT,
EXCEPT।ROW_NUMBER, RANK,
SUM() OVER।WITH clause से readable queries।= NULL कभी match नहीं;
IS NULL use करें।ORDER BY से।
Logical order of execution:
1. FROM / JOIN → working set बनाएँ
2. WHERE → rows filter
3. GROUP BY → groups में collapse
4. HAVING → groups filter
5. SELECT → output columns compute
6. DISTINCT → duplicates हटाएँ
7. ORDER BY → sort
8. LIMIT / OFFSET → paginate
Note: SELECT logically GROUP BY के बाद आता है,
हालाँकि type हम शुरू में करते हैं।
GRANT and REVOKE. Roles group privileges for convenience.
COMMIT, ROLLBACK, SAVEPOINT,
SET TRANSACTION.
-- DCL: grant read-only access to a report user CREATE ROLE analyst; GRANT SELECT ON Student TO analyst; GRANT SELECT ON Department TO analyst; GRANT analyst TO alice; -- Later, revoke one privilege REVOKE SELECT ON Department FROM analyst; -- TCL: transaction with savepoint BEGIN; UPDATE Student SET age = age + 1 WHERE dept_id = 1; SAVEPOINT after_update; DELETE FROM Student WHERE student_id = 999; ROLLBACK TO SAVEPOINT after_update; -- undo only the delete COMMIT; -- keep the update
A. DCL statements:
| Statement | Purpose |
|---|---|
| GRANT | Give privileges (SELECT, INSERT, UPDATE, DELETE, EXECUTE). |
| REVOKE | Take privileges away. |
| CREATE ROLE | Group privileges and assign them to users. |
B. TCL statements:
| Statement | Purpose |
|---|---|
| COMMIT | Make changes permanent. |
| ROLLBACK | Undo changes since last COMMIT or SAVEPOINT. |
| SAVEPOINT | Mark a point inside a transaction to roll back to. |
| SET TRANSACTION | Set isolation level, read-only mode, etc. |
BEGIN
│
▼
INSERT / UPDATE ← SAVEPOINT A
│
▼
DELETE ← SAVEPOINT B
│
▼
ROLLBACK TO B → undo DELETE only
│
▼
COMMIT → keep INSERT / UPDATE
DCL example:
User alice
│
▼
GRANT SELECT ON Student → yes
REVOKE SELECT ON Student → no longer
analyst with SELECT on Student only.GRANT और REVOKE। Roles privileges को group करते
हैं।COMMIT, ROLLBACK,
SAVEPOINT, SET TRANSACTION।-- DCL: read-only access एक report user को CREATE ROLE analyst; GRANT SELECT ON Student TO analyst; GRANT SELECT ON Department TO analyst; GRANT analyst TO alice; -- एक privilege बाद में revoke REVOKE SELECT ON Department FROM analyst; -- TCL: savepoint वाला transaction BEGIN; UPDATE Student SET age = age + 1 WHERE dept_id = 1; SAVEPOINT after_update; DELETE FROM Student WHERE student_id = 999; ROLLBACK TO SAVEPOINT after_update; -- सिर्फ delete undo COMMIT; -- update रहेगा
A. DCL statements:
| Statement | उद्देश्य |
|---|---|
| GRANT | Privileges देना (SELECT, INSERT, UPDATE, DELETE, EXECUTE)। |
| REVOKE | Privileges वापस लेना। |
| CREATE ROLE | Privileges group करके users को assign करना। |
B. TCL statements:
| Statement | उद्देश्य |
|---|---|
| COMMIT | Changes permanent करना। |
| ROLLBACK | पिछले COMMIT या SAVEPOINT के बाद के changes undo करना। |
| SAVEPOINT | Transaction के अंदर एक point mark करना जिस पर roll back कर सकें। |
| SET TRANSACTION | Isolation level, read-only mode आदि set करना। |
BEGIN
│
▼
INSERT / UPDATE ← SAVEPOINT A
│
▼
DELETE ← SAVEPOINT B
│
▼
ROLLBACK TO B → सिर्फ DELETE undo
│
▼
COMMIT → INSERT / UPDATE रहें
DCL उदाहरण:
User alice
│
▼
GRANT SELECT ON Student → हाँ
REVOKE SELECT ON Student → अब नहीं
analyst बनाइए जिसे सिर्फ Student पर SELECT हो।-- VIEW: hide sensitive columns CREATE VIEW StudentPublic AS SELECT student_id, name, dept_id FROM Student; -- INDEX: accelerate search by email CREATE INDEX idx_student_email ON Student(email); -- STORED PROCEDURE CREATE PROCEDURE PromoteStudents(IN minAge INT) BEGIN UPDATE Student SET dept_id = 2 WHERE age >= minAge; END; -- TRIGGER: audit updates CREATE TRIGGER trg_student_audit AFTER UPDATE ON Student FOR EACH ROW INSERT INTO StudentAudit(student_id, changed_at) VALUES (OLD.student_id, NOW());
A. Views:
B. Indexes:
| Type | Use |
|---|---|
| B-tree | Default for equality and range. |
| Hash | Equality only; very fast lookups. |
| Bitmap | Low-cardinality columns (gender, status). |
| Composite | Multiple columns; column order matters. |
| Partial / filtered | Index only a subset of rows. |
| Full-text | Text search (LIKE '%…%' with language rules). |
C. Stored routines and triggers: Procedures (callable by name), functions (return a value), and triggers (fire on events).
v_, idx_,
sp_, trg_ help maintainability.
Application
│ SELECT * FROM StudentPublic
▼
┌──────────────────────┐
│ View: StudentPublic │ ← virtual table
└─────────┬────────────┘
│
▼
┌──────────────────────┐
│ Base Table: Student │
│ Index: idx_email │ ← speeds lookups
└──────────────────────┘
Trigger flow (AFTER UPDATE):
UPDATE Student …
│
▼
Trigger trg_student_audit fires
│
▼
INSERT INTO StudentAudit …
Student(email) and compare query plans before/after.
-- VIEW: sensitive columns छिपाएँ CREATE VIEW StudentPublic AS SELECT student_id, name, dept_id FROM Student; -- INDEX: email से search तेज़ CREATE INDEX idx_student_email ON Student(email); -- STORED PROCEDURE CREATE PROCEDURE PromoteStudents(IN minAge INT) BEGIN UPDATE Student SET dept_id = 2 WHERE age >= minAge; END; -- TRIGGER: audit updates CREATE TRIGGER trg_student_audit AFTER UPDATE ON Student FOR EACH ROW INSERT INTO StudentAudit(student_id, changed_at) VALUES (OLD.student_id, NOW());
A. Views:
B. Indexes:
| प्रकार | उपयोग |
|---|---|
| B-tree | Equality और range के लिए default। |
| Hash | सिर्फ equality; बहुत तेज़ lookups। |
| Bitmap | Low-cardinality columns (gender, status)। |
| Composite | कई columns; column order मायने रखता है। |
| Partial / filtered | सिर्फ rows के subset पर index। |
| Full-text | Text search (LIKE '%…%' with language rules)। |
C. Stored routines और triggers: Procedures (नाम से callable), functions (value return), triggers (events पर fire)।
v_, idx_,
sp_, trg_ maintainability बढ़ाते हैं।
Application
│ SELECT * FROM StudentPublic
▼
┌──────────────────────┐
│ View: StudentPublic │ ← virtual table
└─────────┬────────────┘
│
▼
┌──────────────────────┐
│ Base Table: Student │
│ Index: idx_email │ ← lookups तेज़
└──────────────────────┘
Trigger flow (AFTER UPDATE):
UPDATE Student …
│
▼
Trigger trg_student_audit fire
│
▼
INSERT INTO StudentAudit …
Student(email) पर index बनाकर before/after query plans की तुलना कीजिए।
BEGIN; UPDATE Account SET balance = balance - 100 WHERE id = 'A'; UPDATE Account SET balance = balance + 100 WHERE id = 'B'; COMMIT; If the second UPDATE fails, the first must be undone, otherwise ₹100 disappears. That's Atomicity. If another session reads balance in between, it must not see the intermediate state. That's Isolation. After COMMIT, even if the system crashes, the new balances must be recoverable. That's Durability. The invariant "sum of balances = constant" must hold before and after. That's Consistency.
A. ACID properties:
| Property | Meaning | Guaranteed By |
|---|---|---|
| Atomicity | All or nothing. | Undo log / rollback. |
| Consistency | Preserves invariants and constraints. | Constraints + application logic + triggers. |
| Isolation | Concurrent transactions do not interfere. | Locks, MVCC, isolation levels. |
| Durability | Committed data survives crashes. | Write-ahead log + fsync + replication. |
B. Transaction states:
| State | Meaning |
|---|---|
| Active | Executing statements. |
| Partially committed | Last statement executed; log not yet flushed. |
| Committed | Changes permanent; log flushed. |
| Failed | Error occurred; needs rollback. |
| Aborted | Rolled back; can be retried. |
C. Isolation levels:
| Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|
| READ UNCOMMITTED | Yes | Yes | Yes |
| READ COMMITTED | No | Yes | Yes |
| REPEATABLE READ | No | No | Yes |
| SERIALIZABLE | No | No | No |
Active → Partially Committed → Committed
│ │
│ │
▼ ▼
Failed ──────────► Aborted
Anomalies:
T1: Read(A) Write(A) Commit
T2: Read(A) → dirty read (if T1 aborts)
T1: Read(A) Read(A)
T2: Update(A) ← non-repeatable
T1: SELECT … WHERE age < 30
T2: INSERT age=25 → phantom row seen next time
BEGIN; UPDATE Account SET balance = balance - 100 WHERE id = 'A'; UPDATE Account SET balance = balance + 100 WHERE id = 'B'; COMMIT; अगर दूसरी UPDATE fail हो, पहली undo होनी चाहिए, वरना ₹100 गायब। यही Atomicity है। अगर बीच में कोई दूसरा session balance पढ़े, उसे intermediate state नहीं दिखनी चाहिए। यही Isolation है। COMMIT के बाद system crash हो, नए balances recover होने चाहिए। यही Durability है। "sum of balances = constant" invariant पहले और बाद में hold करे। यही Consistency है।
A. ACID properties:
| Property | मतलब | किससे Guaranteed |
|---|---|---|
| Atomicity | All or nothing। | Undo log / rollback। |
| Consistency | Invariants और constraints preserve। | Constraints + app logic + triggers। |
| Isolation | Concurrent transactions interfere नहीं। | Locks, MVCC, isolation levels। |
| Durability | Committed data crash के बाद भी रहे। | Write-ahead log + fsync + replication। |
B. Transaction states:
| State | मतलब |
|---|---|
| Active | Statements execute हो रही हैं। |
| Partially committed | Last statement execute; log flush नहीं। |
| Committed | Changes permanent; log flush। |
| Failed | Error; rollback चाहिए। |
| Aborted | Rolled back; retry हो सकता है। |
C. Isolation levels:
| Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|
| READ UNCOMMITTED | हाँ | हाँ | हाँ |
| READ COMMITTED | नहीं | हाँ | हाँ |
| REPEATABLE READ | नहीं | नहीं | हाँ |
| SERIALIZABLE | नहीं | नहीं | नहीं |
Active → Partially Committed → Committed
│ │
│ │
▼ ▼
Failed ──────────► Aborted
Anomalies:
T1: Read(A) Write(A) Commit
T2: Read(A) → dirty read (if T1 aborts)
T1: Read(A) Read(A)
T2: Update(A) ← non-repeatable
T1: SELECT … WHERE age < 30
T2: INSERT age=25 → phantom row next time
-- Without locking, Lost Update: T1: READ A (100) T2: READ A (100) T1: WRITE A = 110 T2: WRITE A = 120 ← T1's update lost -- With 2PL, T2 waits until T1 commits: T1: LOCK-X A → WRITE A = 110 → UNLOCK T2: LOCK-X A → WRITE A = 120 → UNLOCK Final A = 120 (correct)
A. Lock modes:
| Lock | Use | Conflict |
|---|---|---|
| Shared (S) | Read | Conflicts with X only. |
| Exclusive (X) | Write | Conflicts with S and X. |
| Intent (IS, IX) | Hierarchical locking (rows/tables). | Prevents conflicts at coarser levels. |
B. Protocols:
| Protocol | Idea |
|---|---|
| 2PL (Basic) | Growing phase acquires locks; shrinking phase releases them. |
| Strict 2PL | Holds X-locks until commit → no dirty reads. |
| Rigorous 2PL | Holds all locks until commit → strictest. |
| Timestamp ordering | Each T has a timestamp; order enforced by timestamp. |
| Optimistic (OCC) | Read → Validate → Write. Good when conflicts rare. |
| MVCC | Readers see a snapshot; writers create new versions. |
C. Anomalies prevented: lost update, dirty read, unrepeatable read, phantom read, write skew.
2PL lifecycle:
GROWING PHASE SHRINKING PHASE
Acquire locks → → Release locks
(no releases allowed) (no new acquires)
Deadlock cycle:
T1 holds A, wants B
│
▼
T2 holds B, wants A
│
▼
Circular wait → deadlock
Detection: build wait-for graph; if cycle, abort one T.
-- Locking के बिना Lost Update: T1: READ A (100) T2: READ A (100) T1: WRITE A = 110 T2: WRITE A = 120 ← T1 का update खो गया -- 2PL के साथ, T2, T1 के commit तक wait: T1: LOCK-X A → WRITE A = 110 → UNLOCK T2: LOCK-X A → WRITE A = 120 → UNLOCK Final A = 120 (सही)
A. Lock modes:
| Lock | उपयोग | Conflict |
|---|---|---|
| Shared (S) | Read | सिर्फ X से conflict। |
| Exclusive (X) | Write | S और X दोनों से conflict। |
| Intent (IS, IX) | Hierarchical locking (rows/tables)। | Coarser levels पर conflicts रोकता है। |
B. Protocols:
| Protocol | Idea |
|---|---|
| 2PL (Basic) | Growing phase locks acquire; shrinking phase release। |
| Strict 2PL | X-locks commit तक hold → कोई dirty read नहीं। |
| Rigorous 2PL | सभी locks commit तक hold → strictest। |
| Timestamp ordering | हर T का timestamp; order timestamp से। |
| Optimistic (OCC) | Read → Validate → Write. Conflicts कम हों तो अच्छा। |
| MVCC | Readers को snapshot; writers नई versions बनाते हैं। |
C. Anomalies prevented: lost update, dirty read, unrepeatable read, phantom read, write skew।
2PL lifecycle:
GROWING PHASE SHRINKING PHASE
Locks acquire → → Locks release
(release नहीं) (नए acquire नहीं)
Deadlock cycle:
T1 के पास A, चाहिए B
│
▼
T2 के पास B, चाहिए A
│
▼
Circular wait → deadlock
Detection: wait-for graph; cycle मिले तो एक T abort।
-- WAL rules: -- 1. Undo entries flushed before any data page is written -- 2. Redo entries flushed before COMMIT returns Log records: LSN 1: T1 BEGIN LSN 2: T1 UPDATE A: 100 → 90 (old=100, new=90) LSN 3: T1 UPDATE B: 200 → 210 (old=200, new=210) LSN 4: T1 COMMIT Crash → Recovery: Analysis : find last checkpoint Redo : replay committed changes from log Undo : roll back uncommitted changes
A. Failure types:
| Failure | Effect | Recovery |
|---|---|---|
| Transaction failure | Bad input, deadlock, constraint violation. | Rollback that T only. |
| System crash | RAM lost, disk intact. | Redo committed; undo uncommitted. |
| Media failure | Disk lost or corrupted. | Restore from backup + redo log. |
B. Log records: BEGIN, UPDATE (with old/new values), COMMIT, ABORT, CLR (compensation log record), CHECKPOINT.
C. Algorithms:
| Algorithm | Idea |
|---|---|
| Deferred update (NO-UNDO/REDO) | Write only after commit; redo on crash. |
| Immediate update (UNDO/REDO) | Write during transaction; undo uncommitted, redo committed. |
| Shadow paging (NO-UNDO/NO-REDO) | Copy-on-write pages; switch pointer on commit. |
| ARIES | Analysis + Redo + Undo with LSN and CLRs. |
Crash
│
▼
1. ANALYSIS
- Read from last checkpoint
- Build Dirty Page Table and Transaction Table
│
▼
2. REDO
- Replay all updates (even of aborted T)
- Idempotent, using LSN
│
▼
3. UNDO
- Roll back uncommitted transactions
- Write CLRs so crash during undo is safe
WAL ordering:
Log record flushed ──► Data page written ──► COMMIT returns
-- WAL rules: -- 1. Undo entries कोई data page लिखने से पहले flush -- 2. Redo entries COMMIT return से पहले flush Log records: LSN 1: T1 BEGIN LSN 2: T1 UPDATE A: 100 → 90 (old=100, new=90) LSN 3: T1 UPDATE B: 200 → 210 (old=200, new=210) LSN 4: T1 COMMIT Crash → Recovery: Analysis : last checkpoint ढूँढो Redo : log से committed changes replay Undo : uncommitted changes roll back
A. Failure types:
| Failure | असर | Recovery |
|---|---|---|
| Transaction failure | Bad input, deadlock, constraint violation। | सिर्फ वह T rollback। |
| System crash | RAM गई, disk ठीक। | Committed redo; uncommitted undo। |
| Media failure | Disk खोया/खराब। | Backup restore + redo log। |
B. Log records: BEGIN, UPDATE (old/new values), COMMIT, ABORT, CLR (compensation log record), CHECKPOINT।
C. Algorithms:
| Algorithm | Idea |
|---|---|
| Deferred update (NO-UNDO/REDO) | सिर्फ commit के बाद write; crash पर redo। |
| Immediate update (UNDO/REDO) | Transaction के दौरान write; uncommitted undo, committed redo। |
| Shadow paging (NO-UNDO/NO-REDO) | Copy-on-write pages; commit पर pointer switch। |
| ARIES | Analysis + Redo + Undo with LSN and CLRs। |
Crash
│
▼
1. ANALYSIS
- Last checkpoint से पढ़ो
- Dirty Page Table और Transaction Table बनाओ
│
▼
2. REDO
- सभी updates replay (aborted T के भी)
- Idempotent, LSN से
│
▼
3. UNDO
- Uncommitted transactions roll back
- CLRs लिखो ताकि undo के दौरान crash safe हो
WAL ordering:
Log record flush ──► Data page write ──► COMMIT return
CREATE INDEX idx_student_email ON Student(email); Query (uses index): SELECT * FROM Student WHERE email = 'a@x.com'; → O(log n) instead of O(n) Range query (uses index): SELECT * FROM Student WHERE email BETWEEN 'a' AND 'b'; Covering index (no table lookup needed): CREATE INDEX idx_dept_name ON Student(dept_id, name); SELECT dept_id, name FROM Student WHERE dept_id = 1;
A. Index types:
| Type | Good For | Notes |
|---|---|---|
| B+ tree | Equality + range | Default; balanced; ordered. |
| Hash | Equality only | Very fast lookups; no range scans. |
| Bitmap | Low-cardinality columns | Compact; good for analytics. |
| Composite | Multi-column queries | Column order matters (leftmost prefix). |
| Covering | Read-heavy queries | No table lookup if all columns in index. |
| Full-text | Word search | Supports stemming and ranking. |
| Partial / filtered | Subset of rows | Smaller, faster; e.g., WHERE active = TRUE. |
B. Hash-based structures: static hashing, extendible hashing, linear hashing. Used for in-memory and equality lookups.
B+ Tree (order 3):
[ 20 | 40 ]
/ | \
[5|10] [25|35] [45|60]
/ | \ / | \ / | \
5 10 15 20 25 35 40 45 60 ← leaves (linked)
◄────────────────────────────► range scan
Query access paths:
WHERE id = 42 → index seek (O(log n))
WHERE id BETWEEN 10 AND 40 → index range scan
WHERE name LIKE '%a%' → full scan (index unusable)
Clustered vs non-clustered:
Clustered: table rows physically sorted by index key
Non-clustered: index stores pointers to rows
CREATE INDEX idx_student_email ON Student(email); Query (index use): SELECT * FROM Student WHERE email = 'a@x.com'; → O(n) के बजाय O(log n) Range query (index use): SELECT * FROM Student WHERE email BETWEEN 'a' AND 'b'; Covering index (table lookup नहीं): CREATE INDEX idx_dept_name ON Student(dept_id, name); SELECT dept_id, name FROM Student WHERE dept_id = 1;
A. Index types:
| Type | किसके लिए अच्छा | Notes |
|---|---|---|
| B+ tree | Equality + range | Default; balanced; ordered। |
| Hash | सिर्फ equality | बहुत तेज़ lookups; range नहीं। |
| Bitmap | Low-cardinality columns | Compact; analytics के लिए अच्छा। |
| Composite | Multi-column queries | Column order मायने रखता है (leftmost prefix)। |
| Covering | Read-heavy queries | सभी columns index में हों तो table lookup नहीं। |
| Full-text | Word search | Stemming और ranking support। |
| Partial / filtered | Subset of rows | छोटा, तेज़; जैसे WHERE active = TRUE। |
B. Hash-based structures: static hashing, extendible hashing, linear hashing। In-memory और equality lookups के लिए।
B+ Tree (order 3):
[ 20 | 40 ]
/ | \
[5|10] [25|35] [45|60]
/ | \ / | \ / | \
5 10 15 20 25 35 40 45 60 ← leaves (linked)
◄────────────────────────────► range scan
Query access paths:
WHERE id = 42 → index seek (O(log n))
WHERE id BETWEEN 10 AND 40 → index range scan
WHERE name LIKE '%a%' → full scan (index unusable)
Clustered vs non-clustered:
Clustered: rows physically index key से sorted
Non-clustered: index pointers to rows रखता है
EXPLAIN shows the plan.
SELECT c.name
FROM Customer c JOIN Orders o ON c.id = o.cust_id
WHERE o.date >= '2025-01-01';
Plan A (bad): full scan Orders, full scan Customer,
nested loop join
Plan B (good): use index on Orders(date),
hash join with Customer
View plans in PostgreSQL / MySQL:
EXPLAIN ANALYZE SELECT ...
A. Join algorithms:
| Algorithm | Best When |
|---|---|
| Nested loop join | Small outer table, indexed inner. |
| Block nested loop | No indexes, memory-limited. |
| Hash join | Large tables, equality join. |
| Sort-merge join | Inputs already sorted or need order. |
B. Optimization phases:
| Phase | Purpose |
|---|---|
| Parsing | Syntax + semantic checks; build parse tree. |
| Logical rewrite | Relational algebra transformations; predicate pushdown; view expansion. |
| Physical planning | Choose access paths, join algorithms, join order. |
| Cost estimation | Use statistics to estimate I/O + CPU; pick cheapest. |
| Execution | Run the chosen plan; produce results. |
C. Heuristics: Push selections down; project early; avoid Cartesian products; use indexes when selective; join smaller relations first.
SQL text
│
▼
Parser → Parse Tree
│
▼
Rewriter → Logical Plan (relational algebra)
│
▼
Optimizer
│ ├── Statistics (table, columns, indexes)
│ ├── Cost model (I/O + CPU + network)
│ ├── Search (join orders, algorithms, access paths)
│ └── Choose lowest cost plan
│
▼
Physical Plan
│
▼
Executor → Results
EXPLAIN output (simplified):
Hash Join (cost=… rows=…)
├─ Seq Scan on Customer
└─ Index Scan on Orders (date >= …)
EXPLAIN plan दिखाता है।
SELECT c.name
FROM Customer c JOIN Orders o ON c.id = o.cust_id
WHERE o.date >= '2025-01-01';
Plan A (खराब): Orders full scan, Customer full scan,
nested loop join
Plan B (अच्छा): Orders(date) पर index use,
hash join with Customer
PostgreSQL / MySQL में plan देखें:
EXPLAIN ANALYZE SELECT ...
A. Join algorithms:
| Algorithm | कब अच्छा |
|---|---|
| Nested loop join | छोटी outer, indexed inner। |
| Block nested loop | Index नहीं, memory-limited। |
| Hash join | बड़ी tables, equality join। |
| Sort-merge join | Inputs पहले से sorted या order चाहिए। |
B. Optimization phases:
| Phase | उद्देश्य |
|---|---|
| Parsing | Syntax + semantic checks; parse tree। |
| Logical rewrite | Relational algebra transformations; predicate pushdown; view expansion। |
| Physical planning | Access paths, join algorithms, join order चुनें। |
| Cost estimation | Statistics से I/O + CPU estimate; सबसे सस्ता चुनें। |
| Execution | Chuna gaya plan चलाएँ; results। |
C. Heuristics: Selections नीचे push करें; जल्दी project करें; Cartesian products से बचें; selective हो तो index use करें; छोटी relations पहले join करें।
SQL text
│
▼
Parser → Parse Tree
│
▼
Rewriter → Logical Plan (relational algebra)
│
▼
Optimizer
│ ├── Statistics (table, columns, indexes)
│ ├── Cost model (I/O + CPU + network)
│ ├── Search (join orders, algorithms, access paths)
│ └── Lowest cost plan चुनें
│
▼
Physical Plan
│
▼
Executor → Results
EXPLAIN output (सरलीकृत):
Hash Join (cost=… rows=…)
├─ Seq Scan on Customer
└─ Index Scan on Orders (date >= …)
-- Document (MongoDB): flexible JSON-like documents
db.users.insertOne({
name: "Amit",
emails: ["a@x.com", "amit@y.com"],
address: { city: "Delhi" }
});
-- Key-Value (Redis):
SET session:123 "user_id=42"
GET session:123
-- Column-family (Cassandra):
CREATE TABLE events (user_id UUID, ts TIMESTAMP,
event TEXT, PRIMARY KEY (user_id, ts));
-- Graph (Neo4j):
MATCH (a:Person)-[:FRIEND]->(b:Person)
WHERE a.name = 'Amit' RETURN b.name;
A. NoSQL categories:
| Category | Model | Examples | Best For |
|---|---|---|---|
| Document | JSON/BSON docs | MongoDB, CouchDB | Catalogs, CMS, user profiles |
| Key-value | Map of key → value | Redis, DynamoDB, Riak | Sessions, cache, queues |
| Column-family | Rows with flexible columns | Cassandra, HBase, ScyllaDB | Time series, IoT, logs |
| Graph | Nodes + edges + properties | Neo4j, JanusGraph | Social, recommendations, fraud |
| Search | Inverted index | Elasticsearch, Solr | Full-text search, analytics |
| Time-series | Timestamped data | InfluxDB, TimescaleDB | Metrics, IoT, monitoring |
B. CAP theorem: Under a network partition, choose either CP (Consistency + Partition tolerance) or AP (Availability + Partition tolerance). You cannot have all three.
C. NewSQL: CockroachDB, Google Spanner, TiDB — SQL + ACID + horizontal scaling.
CAP Theorem:
Consistency
▲
╱ ╲
╱ ╲
╱ CA ╲
╱ (RDBMS)╲
╱ ╲
CP ╱──────────────╲ AP
╱ MongoDB, Redis ╲ Cassandra,
╱ HBase ╲ DynamoDB
▼────────────────────▼
Partition Tolerance
Polyglot persistence:
App → Users → PostgreSQL (ACID)
→ Sessions → Redis
→ Catalog → MongoDB
→ Metrics → InfluxDB
→ Social → Neo4j
-- Document (MongoDB): flexible JSON-like documents
db.users.insertOne({
name: "अमित",
emails: ["a@x.com", "amit@y.com"],
address: { city: "दिल्ली" }
});
-- Key-Value (Redis):
SET session:123 "user_id=42"
GET session:123
-- Column-family (Cassandra):
CREATE TABLE events (user_id UUID, ts TIMESTAMP,
event TEXT, PRIMARY KEY (user_id, ts));
-- Graph (Neo4j):
MATCH (a:Person)-[:FRIEND]->(b:Person)
WHERE a.name = 'अमित' RETURN b.name;
A. NoSQL categories:
| Category | Model | Examples | Best For |
|---|---|---|---|
| Document | JSON/BSON docs | MongoDB, CouchDB | Catalogs, CMS, user profiles। |
| Key-value | Map of key → value | Redis, DynamoDB, Riak | Sessions, cache, queues। |
| Column-family | Flexible columns वाली rows | Cassandra, HBase, ScyllaDB | Time series, IoT, logs। |
| Graph | Nodes + edges + properties | Neo4j, JanusGraph | Social, recommendations, fraud। |
| Search | Inverted index | Elasticsearch, Solr | Full-text search, analytics। |
| Time-series | Timestamped data | InfluxDB, TimescaleDB | Metrics, IoT, monitoring। |
B. CAP theorem: Network partition में या CP (Consistency + Partition tolerance) चुनें या AP (Availability + Partition tolerance)। तीनों एक साथ नहीं।
C. NewSQL: CockroachDB, Google Spanner, TiDB — SQL + ACID + horizontal scaling।
CAP Theorem:
Consistency
▲
╱ ╲
╱ ╲
╱ CA ╲
╱ (RDBMS)╲
╱ ╲
CP ╱──────────────╲ AP
╱ MongoDB, Redis ╲ Cassandra,
╱ HBase ╲ DynamoDB
▼────────────────────▼
Partition Tolerance
Polyglot persistence:
App → Users → PostgreSQL (ACID)
→ Sessions → Redis
→ Catalog → MongoDB
→ Metrics → InfluxDB
→ Social → Neo4j