01
Unit 1
Introduction to SQL
What it is, categories, data types
SQL = Structured Query Language. Declarative — you say WHAT you want, not HOW. The DBMS optimizer decides the execution plan. ANSI/ISO standard since 1987 (originated at IBM as SEQUEL).
Key Characteristics
- Non-procedural — specify WHAT, not HOW
- Set-oriented — operates on entire sets of rows at once
- Standardized — portable across MySQL, Oracle, PostgreSQL, SQL Server
- Comprehensive — DDL + DML + DCL + TCL in one language
- Human-readable — English-like keywords
SQL Command Categories
| Category | Commands | Purpose |
|---|---|---|
| DDL | CREATE, ALTER, DROP, TRUNCATE | Define structure |
| DML | SELECT, INSERT, UPDATE, DELETE | Manipulate data |
| DCL | GRANT, REVOKE | Access control |
| TCL | COMMIT, ROLLBACK, SAVEPOINT | Transaction control |
SQL Data Types ▼
| Type | Description | Example |
|---|---|---|
| INT / INTEGER | Whole numbers | Age INT |
| DECIMAL(p,s) | Fixed-point (p=precision, s=scale) | Price DECIMAL(8,2) |
| FLOAT / REAL | Approximate floating-point | Score FLOAT |
| CHAR(n) | Fixed-length string | Gender CHAR(1) |
| VARCHAR(n) | Variable-length string (max n) | Name VARCHAR(50) |
| DATE | YYYY-MM-DD | DOB DATE |
| TIME | HH:MM:SS | Login TIME |
| TIMESTAMP | Date + Time | Created TIMESTAMP |
| BOOLEAN | TRUE / FALSE | Active BOOLEAN |
| BLOB | Binary large object | Photo BLOB |
| TEXT | Large text | Bio TEXT |
Exam tip: CHAR wastes space but is faster. VARCHAR saves space. DECIMAL is exact; FLOAT is approximate — use DECIMAL for money.
02
DDL
Data Definition Language
CREATE, ALTER, DROP, TRUNCATE, INDEX
CREATE TABLE with Constraints
CREATE TABLE STUDENT ( Student_ID INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Age INT CHECK (Age BETWEEN 15 AND 35), Gender CHAR(1) CHECK (Gender IN ('M','F','O')), Email VARCHAR(100) UNIQUE, Dept_ID INT, FOREIGN KEY (Dept_ID) REFERENCES DEPARTMENT(Dept_ID) ON DELETE SET NULL ON UPDATE CASCADE );
Constraints Summary
| Constraint | Rule |
|---|---|
| PRIMARY KEY | Unique + NOT NULL. One per table. |
| NOT NULL | Column cannot be empty |
| UNIQUE | All values distinct (NULLs allowed) |
| CHECK | Value must satisfy a condition |
| DEFAULT | Value used when none provided |
| FOREIGN KEY | References PK of another table |
Foreign Key Actions
| Action | What happens to FK rows |
|---|---|
| RESTRICT | Block the operation ❌ |
| CASCADE | Propagate change/delete automatically |
| SET NULL | Set FK to NULL |
| SET DEFAULT | Set FK to default value |
ALTER TABLE
ALTER TABLE STUDENT ADD COLUMN Phone VARCHAR(15); ALTER TABLE STUDENT MODIFY COLUMN Name VARCHAR(100); ALTER TABLE STUDENT DROP COLUMN Phone; ALTER TABLE STUDENT ADD CONSTRAINT chk CHECK (Age >= 15); ALTER TABLE STUDENT DROP CONSTRAINT chk;
DROP vs TRUNCATE vs DELETE
| Command | Removes | Structure? | Rollback? |
|---|---|---|---|
| DROP TABLE | Everything including table | ❌ Gone | ❌ |
| TRUNCATE | All rows, keeps structure | ✅ Stays | ❌ (DDL) |
| DELETE | Specific rows (WHERE) | ✅ Stays | ✅ (DML) |
CREATE INDEX
CREATE INDEX idx_name ON STUDENT (Name); CREATE UNIQUE INDEX idx_email ON STUDENT (Email); DROP INDEX idx_name ON STUDENT;
Indexes speed up queries but slow down INSERT/UPDATE/DELETE. Trade-off: query speed vs write speed.
Exam tip: TRUNCATE is DDL (can't rollback). DELETE is DML (can rollback). PRIMARY KEY = UNIQUE + NOT NULL combined.
03
DML
SQL DML — Queries & Joins
SELECT, INSERT, UPDATE, DELETE, all JOIN types
SELECT Statement Structure
SELECT [DISTINCT] columns FROM table(s) [WHERE condition] [GROUP BY column] [HAVING group_condition] [ORDER BY column [ASC|DESC]];
Execution order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
WHERE Operators
| Operator | Usage | Example |
|---|---|---|
| BETWEEN | Inclusive range | Age BETWEEN 18 AND 25 |
| IN | Match any in list | Dept IN ('CS','IT') |
| LIKE | Pattern match | Name LIKE 'A%' |
| IS NULL | Check for NULL | Email IS NULL |
| NOT IN / NOT LIKE | Negation | Dept NOT IN ('EC') |
LIKE patterns:
% = any chars |
_ = one char
'A%' starts with A · '%Kumar' ends with Kumar · '_r%' 2nd char is r
'A%' starts with A · '%Kumar' ends with Kumar · '_r%' 2nd char is r
JOIN Types
Matching rows only
All left + matches
All right + matches
All rows, both sides
Every combo (m×n rows)
Table joins itself
| JOIN | Returns | NULL-filled side |
|---|---|---|
| INNER JOIN | Only matching rows | Neither |
| LEFT JOIN | All left + matching right | Right (non-matches) |
| RIGHT JOIN | All right + matching left | Left (non-matches) |
| FULL OUTER JOIN | All rows both tables | Both sides |
| CROSS JOIN | Cartesian product (m × n) | — |
| SELF JOIN | Table joined to itself | — |
JOIN Syntax Examples
-- INNER JOIN SELECT s.Name, d.Dept_Name FROM STUDENT s INNER JOIN DEPARTMENT d ON s.Dept_ID = d.Dept_ID; -- LEFT JOIN (all students, even without dept) SELECT s.Name, d.Dept_Name FROM STUDENT s LEFT JOIN DEPARTMENT d ON s.Dept_ID = d.Dept_ID; -- SELF JOIN (employee and their manager) SELECT e1.Name AS Employee, e2.Name AS Manager FROM EMPLOYEE e1 JOIN EMPLOYEE e2 ON e1.Manager_ID = e2.Employee_ID; -- CROSS JOIN SELECT s.Name, c.Course_Name FROM STUDENT s CROSS JOIN COURSE c;
INSERT / UPDATE / DELETE
-- INSERT INSERT INTO STUDENT VALUES (104, 'Meena', 20, 'F', '[email protected]', 'CS'); INSERT INTO STUDENT (Student_ID, Name) VALUES (105, 'Arjun'); INSERT INTO STUDENT SELECT * FROM NEW_ADMISSIONS WHERE Year = 2024; -- UPDATE UPDATE STUDENT SET Age = 21 WHERE Student_ID = 101; -- DELETE DELETE FROM STUDENT WHERE Student_ID = 105;
Exam tip: No WHERE in UPDATE/DELETE = affects ALL rows! CROSS JOIN with 100 × 10 rows = 1000 rows. INNER JOIN ≠ OUTER JOIN — know which returns NULLs.
04
Advanced SQL
Aggregation, Subqueries, Views, Triggers
Aggregate Functions
| Function | Does | NULL behavior |
|---|---|---|
| COUNT(*) | Count all rows | Counts NULLs |
| COUNT(col) | Count non-NULL values | Ignores NULLs |
| SUM(col) | Total sum | Ignores NULLs |
| AVG(col) | Average value | Ignores NULLs |
| MAX(col) | Largest value | Ignores NULLs |
| MIN(col) | Smallest value | Ignores NULLs |
GROUP BY + HAVING
WHERE filters rows BEFORE grouping | HAVING filters groups AFTER aggregation
-- Count students per dept (only depts with > 50 students) SELECT Dept_ID, COUNT(*) AS Total FROM STUDENT WHERE Age > 17 -- filter rows first GROUP BY Dept_ID HAVING COUNT(*) > 50 -- filter groups after ORDER BY Total DESC;
Nested Queries (Subqueries)
Non-Correlated Subquery
Inner query is independent — executes ONCE, result passed to outer query
Correlated Subquery
Inner query depends on outer row — executes once per outer row (slower)
-- Non-correlated: find CS students SELECT Name FROM STUDENT WHERE Dept_ID = (SELECT Dept_ID FROM DEPARTMENT WHERE Dept_Name = 'CS'); -- Correlated: students above their dept avg SELECT s.Name, m.Marks FROM STUDENT s JOIN MARKS m ON s.Student_ID = m.Student_ID WHERE m.Marks > ( SELECT AVG(m2.Marks) FROM MARKS m2 JOIN STUDENT s2 ON m2.Student_ID = s2.Student_ID WHERE s2.Dept_ID = s.Dept_ID -- references outer query );
Subquery Operators
| Operator | Meaning | Example |
|---|---|---|
| IN | Matches any value in subquery result | WHERE Dept_ID IN (SELECT ...) |
| NOT IN | Doesn't match any value | WHERE ID NOT IN (SELECT ...) |
| EXISTS | TRUE if subquery returns ≥1 row | WHERE EXISTS (SELECT 1 FROM ...) |
| NOT EXISTS | TRUE if subquery returns 0 rows | WHERE NOT EXISTS (...) |
| ANY / SOME | True if condition holds for at least one | WHERE Marks > ANY (...) |
| ALL | True if condition holds for all | WHERE Marks > ALL (...) |
-- EXISTS: students enrolled in at least one course SELECT Name FROM STUDENT s WHERE EXISTS (SELECT 1 FROM ENROLLMENT e WHERE e.Student_ID = s.Student_ID); -- ALL: students scoring more than every CS student SELECT Name FROM MARKS WHERE Marks > ALL (SELECT Marks FROM MARKS WHERE Dept_ID = 'CS');
Views
A View is a virtual table — a saved SELECT query. Does NOT store data physically. Computed dynamically when queried.
-- Create view CREATE VIEW CS_Students AS SELECT Student_ID, Name, Age FROM STUDENT WHERE Dept_ID = 'CS'; -- Use like a table SELECT * FROM CS_Students WHERE Age > 20; -- Drop view DROP VIEW CS_Students;
| Benefit | How |
|---|---|
| Security | Hide sensitive columns — expose only what user needs |
| Simplicity | Hide complex joins behind a simple virtual table |
| Independence | Redefine view if base table changes |
Assertions
General integrity constraint not tied to any single table. Defined in SQL standard but not widely implemented in practice.
-- Max 60 students per course CREATE ASSERTION max_enrollment CHECK ( NOT EXISTS ( SELECT Course_ID FROM ENROLLMENT GROUP BY Course_ID HAVING COUNT(*) > 60 ) );
Triggers
A Trigger is a stored procedure that fires automatically on INSERT / UPDATE / DELETE. Used for audit logs, business rules, derived data.
| Type | When it fires |
|---|---|
| BEFORE INSERT | Before a new row is inserted |
| AFTER INSERT | After new row is inserted |
| BEFORE UPDATE | Before a row is updated |
| AFTER UPDATE | After a row is updated |
| BEFORE DELETE | Before a row is deleted |
| AFTER DELETE | After a row is deleted |
-- Trigger: auto-deduct stock on order CREATE TRIGGER update_stock AFTER INSERT ON ORDER_ITEM FOR EACH ROW BEGIN UPDATE PRODUCT SET Stock = Stock - NEW.Quantity WHERE Product_ID = NEW.Product_ID; END; -- Trigger: audit salary changes CREATE TRIGGER log_salary AFTER UPDATE OF Salary ON EMPLOYEE FOR EACH ROW BEGIN INSERT INTO SALARY_LOG VALUES (OLD.Employee_ID, OLD.Salary, NEW.Salary, NOW()); END;
NEW = new row values (INSERT/UPDATE) | OLD = old row values (UPDATE/DELETE)
Exam tip: WHERE filters rows, HAVING filters groups. EXISTS is faster than IN for large datasets. Views don't store data — they're stored queries. NEW/OLD keywords are critical in triggers.
05
NoSQL
Introduction to NoSQL Databases
Why NoSQL, types, ACID vs BASE, CAP theorem
Why NoSQL?
- Data is unstructured / semi-structured (JSON, XML, images)
- Schema changes frequently — rigid tables don't work
- High velocity — millions of records per second
- Need to scale horizontally (add servers, not bigger servers)
- RDBMS can't handle this cost-effectively at web scale
NoSQL Database Types
| Type | Model | Examples | Best For |
|---|---|---|---|
| Key-Value | key → value | Redis, DynamoDB | Cache, sessions, preferences |
| Document | JSON/BSON docs | MongoDB, CouchDB | Content mgmt, catalogs |
| Column-Family | Column groups | Cassandra, HBase | Time-series, IoT, analytics |
| Graph | Nodes & edges | Neo4j, Neptune | Social networks, recommendations |
ACID vs BASE
| ACID (Relational) | BASE (NoSQL) |
|---|---|
| Atomicity — all or nothing | Basically Available — always responds |
| Consistency — always valid state | Soft state — state may change over time |
| Isolation — no interference | Eventual Consistency — becomes consistent eventually |
| Durability — committed = permanent | Prioritizes availability over strict consistency |
| Strong consistency | Weak consistency, better performance & scale |
CAP Theorem (Brewer's Theorem)
A distributed database can guarantee at most 2 of these 3 properties simultaneously:
Consistency
every read = latest
Availability
always responds
Partition Tolerance
survives network splits
Choose at most 2: CA, CP, or AP.
| Choice | Gives up | Example systems |
|---|---|---|
| CA | Partition Tolerance | Traditional RDBMS |
| CP | Availability | HBase, Zookeeper, MongoDB |
| AP | Consistency | Cassandra, CouchDB, DynamoDB |
Exam tip: CAP says choose 2 of 3. In practice, Partition Tolerance is mandatory for distributed systems, so the real choice is C vs A. "Eventual consistency" = BASE's answer to giving up C temporarily.
06
NoSQL DBs
Redis & MongoDB
Key-value and Document databases
Redis
Key-Value Store
Remote Dictionary Server
- In-memory — all data in RAM → sub-millisecond latency
- Persistence — RDB snapshots + AOF (append-only file) log
- Atomic operations — all commands atomic
- TTL — keys expire automatically (great for caching/sessions)
- Pub/Sub — publish/subscribe messaging
| Data Type | Commands | Use Case |
|---|---|---|
| String | SET, GET, INCR, DECR, EXPIRE | Counters, tokens, cache |
| List | LPUSH, RPUSH, LPOP, LRANGE | Queues, timelines |
| Set | SADD, SMEMBERS, SUNION | Tags, unique visitors |
| Sorted Set | ZADD, ZRANGE, ZRANK | Leaderboards |
| Hash | HSET, HGET, HGETALL | Object/user profiles |
-- String: store and retrieve SET username:101 'Arun Kumar' GET username:101 -- Returns: 'Arun Kumar' EXPIRE username:101 3600 -- Expires in 1 hour -- Hash: store object HSET user:101 name 'Arun' age 20 dept 'CS' HGETALL user:101 -- Sorted Set: leaderboard ZADD leaderboard 1500 'Arun' ZRANGE leaderboard 0 9 WITHSCORES -- Top 10
Redis Use Cases
Session management
Query result caching
Rate limiting
Leaderboards
Job queues
Real-time analytics
MongoDB
Document Store
JSON/BSON documents
- Schema-less — documents in same collection can have different fields
- Nested documents — embed related data (no joins needed)
- Horizontal scalability — built-in sharding
- Replica sets — automatic failover for high availability
- Rich query language — filter, sort, project, aggregate
| SQL Term | MongoDB Term |
|---|---|
| Database | Database |
| Table | Collection |
| Row / Record | Document |
| Column | Field |
| Primary Key | _id (auto-created) |
| JOIN | $lookup (aggregation) |
| Schema | No fixed schema (flexible) |
// Document example { _id: ObjectId('64a1b2c3...'), student_id: 101, name: 'Arun Kumar', courses: ['DBMS', 'OS', 'CN'], // array field address: { city: 'Bangalore', pin: '560001' } // nested doc } // INSERT db.students.insertOne({ student_id: 101, name: 'Arun', dept: 'CS' }); // FIND (SELECT) db.students.find({ dept: 'CS' }); db.students.find({ age: { $gt: 20 } }, { name: 1, dept: 1, _id: 0 }); // UPDATE db.students.updateOne({ student_id: 101 }, { $set: { age: 21 } }); // DELETE db.students.deleteOne({ student_id: 101 });
Redis vs MongoDB vs SQL
| Aspect | Redis | MongoDB | SQL (RDBMS) |
|---|---|---|---|
| Data Model | Key-Value | Documents (JSON) | Tables (rows/cols) |
| Storage | In-memory (RAM) | Disk-based | Disk-based |
| Speed | Fastest (<1ms) | Fast | Moderate |
| Schema | None | Flexible | Fixed/strict |
| Query | Key lookup only | Rich queries | Full SQL |
| Relations | No | $lookup / embed | JOINs |
| Best for | Cache, sessions | Content, catalogs | Structured data |
| Consistency | Eventual | Configurable | Strong (ACID) |
Exam tip: Redis = RAM = fastest but limited size. MongoDB = disk = rich queries on flexible docs. SQL = rigid schema but strong ACID. Redis TTL makes it ideal for sessions/cache.
FC
Study Mode
Flashcards
Tap card to reveal answer
∑
Quick Ref
Master Cheatsheet
SQL Command Quick Reference
| Need to… | Use |
|---|---|
| Create a table | CREATE TABLE t (...) |
| Add a column | ALTER TABLE t ADD COLUMN col TYPE |
| Remove table entirely | DROP TABLE t |
| Empty table, keep structure | TRUNCATE TABLE t |
| Filter rows | WHERE condition |
| Remove duplicates | SELECT DISTINCT |
| Sort results | ORDER BY col ASC/DESC |
| Group + count | GROUP BY col |
| Filter groups | HAVING aggregate_condition |
| Pattern match | LIKE 'A%' or '_r%' |
| Check for empty | IS NULL / IS NOT NULL |
| Match list | IN ('CS','IT') |
| Range inclusive | BETWEEN 10 AND 20 |
| Check row exists | EXISTS (subquery) |
| Compare to subquery set | ANY / ALL |
All Facts in One Table
| Topic | Key Rule |
|---|---|
| SQL paradigm | Declarative — WHAT not HOW |
| CHAR vs VARCHAR | CHAR fixed (faster), VARCHAR variable (saves space) |
| PK constraint | UNIQUE + NOT NULL combined |
| TRUNCATE vs DELETE | TRUNCATE = DDL (no rollback); DELETE = DML (rollback ok) |
| FK ON DELETE CASCADE | Child rows deleted when parent deleted |
| SQL exec order | FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY |
| INNER JOIN | Only rows with matches in BOTH tables |
| LEFT JOIN | All left + matching right (NULL if no right match) |
| CROSS JOIN rows | m × n (Cartesian product) |
| WHERE vs HAVING | WHERE = before grouping; HAVING = after aggregation |
| COUNT(*) vs COUNT(col) | COUNT(*) includes NULLs; COUNT(col) ignores NULLs |
| Correlated subquery | Depends on outer row → runs once per outer row |
| EXISTS | Returns TRUE if subquery has ≥1 row |
| View | Virtual table — stored query, no physical data |
| Trigger NEW/OLD | NEW = new values; OLD = old values |
| NoSQL BASE | Basically Available, Soft state, Eventually consistent |
| CAP theorem | Choose max 2 of: Consistency, Availability, Partition Tolerance |
| Redis storage | In-memory (RAM) → sub-millisecond |
| MongoDB collection | = SQL table. Document = row. Field = column. _id = PK |
| Horizontal scale | Add more servers (NoSQL); vertical = bigger server (RDBMS) |