MODULE 03
QUERY LANGUAGES — SQL & NoSQL
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

CategoryCommandsPurpose
DDLCREATE, ALTER, DROP, TRUNCATEDefine structure
DMLSELECT, INSERT, UPDATE, DELETEManipulate data
DCLGRANT, REVOKEAccess control
TCLCOMMIT, ROLLBACK, SAVEPOINTTransaction control
SQL Data Types
TypeDescriptionExample
INT / INTEGERWhole numbersAge INT
DECIMAL(p,s)Fixed-point (p=precision, s=scale)Price DECIMAL(8,2)
FLOAT / REALApproximate floating-pointScore FLOAT
CHAR(n)Fixed-length stringGender CHAR(1)
VARCHAR(n)Variable-length string (max n)Name VARCHAR(50)
DATEYYYY-MM-DDDOB DATE
TIMEHH:MM:SSLogin TIME
TIMESTAMPDate + TimeCreated TIMESTAMP
BOOLEANTRUE / FALSEActive BOOLEAN
BLOBBinary large objectPhoto BLOB
TEXTLarge textBio 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

ConstraintRule
PRIMARY KEYUnique + NOT NULL. One per table.
NOT NULLColumn cannot be empty
UNIQUEAll values distinct (NULLs allowed)
CHECKValue must satisfy a condition
DEFAULTValue used when none provided
FOREIGN KEYReferences PK of another table

Foreign Key Actions

ActionWhat happens to FK rows
RESTRICTBlock the operation ❌
CASCADEPropagate change/delete automatically
SET NULLSet FK to NULL
SET DEFAULTSet 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

CommandRemovesStructure?Rollback?
DROP TABLEEverything including table❌ Gone
TRUNCATEAll rows, keeps structure✅ Stays❌ (DDL)
DELETESpecific 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

OperatorUsageExample
BETWEENInclusive rangeAge BETWEEN 18 AND 25
INMatch any in listDept IN ('CS','IT')
LIKEPattern matchName LIKE 'A%'
IS NULLCheck for NULLEmail IS NULL
NOT IN / NOT LIKENegationDept NOT IN ('EC')
LIKE patterns:   % = any chars  |  _ = one char
'A%' starts with A  ·  '%Kumar' ends with Kumar  ·  '_r%' 2nd char is r

JOIN Types

INNER JOIN
Matching rows only
LEFT JOIN
All left + matches
RIGHT JOIN
All right + matches
FULL OUTER
All rows, both sides
CROSS JOIN
Every combo (m×n rows)
SELF JOIN
Table joins itself
JOINReturnsNULL-filled side
INNER JOINOnly matching rowsNeither
LEFT JOINAll left + matching rightRight (non-matches)
RIGHT JOINAll right + matching leftLeft (non-matches)
FULL OUTER JOINAll rows both tablesBoth sides
CROSS JOINCartesian product (m × n)
SELF JOINTable 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

FunctionDoesNULL behavior
COUNT(*)Count all rowsCounts NULLs
COUNT(col)Count non-NULL valuesIgnores NULLs
SUM(col)Total sumIgnores NULLs
AVG(col)Average valueIgnores NULLs
MAX(col)Largest valueIgnores NULLs
MIN(col)Smallest valueIgnores 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

OperatorMeaningExample
INMatches any value in subquery resultWHERE Dept_ID IN (SELECT ...)
NOT INDoesn't match any valueWHERE ID NOT IN (SELECT ...)
EXISTSTRUE if subquery returns ≥1 rowWHERE EXISTS (SELECT 1 FROM ...)
NOT EXISTSTRUE if subquery returns 0 rowsWHERE NOT EXISTS (...)
ANY / SOMETrue if condition holds for at least oneWHERE Marks > ANY (...)
ALLTrue if condition holds for allWHERE 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;
BenefitHow
SecurityHide sensitive columns — expose only what user needs
SimplicityHide complex joins behind a simple virtual table
IndependenceRedefine 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.
TypeWhen it fires
BEFORE INSERTBefore a new row is inserted
AFTER INSERTAfter new row is inserted
BEFORE UPDATEBefore a row is updated
AFTER UPDATEAfter a row is updated
BEFORE DELETEBefore a row is deleted
AFTER DELETEAfter 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

TypeModelExamplesBest For
Key-Valuekey → valueRedis, DynamoDBCache, sessions, preferences
DocumentJSON/BSON docsMongoDB, CouchDBContent mgmt, catalogs
Column-FamilyColumn groupsCassandra, HBaseTime-series, IoT, analytics
GraphNodes & edgesNeo4j, NeptuneSocial networks, recommendations

ACID vs BASE

ACID (Relational)BASE (NoSQL)
Atomicity — all or nothingBasically Available — always responds
Consistency — always valid stateSoft state — state may change over time
Isolation — no interferenceEventual Consistency — becomes consistent eventually
Durability — committed = permanentPrioritizes availability over strict consistency
Strong consistencyWeak 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
C
Availability
always responds
A
Partition Tolerance
survives network splits
P
Choose at most 2: CA, CP, or AP.
ChoiceGives upExample systems
CAPartition ToleranceTraditional RDBMS
CPAvailabilityHBase, Zookeeper, MongoDB
APConsistencyCassandra, 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 TypeCommandsUse Case
StringSET, GET, INCR, DECR, EXPIRECounters, tokens, cache
ListLPUSH, RPUSH, LPOP, LRANGEQueues, timelines
SetSADD, SMEMBERS, SUNIONTags, unique visitors
Sorted SetZADD, ZRANGE, ZRANKLeaderboards
HashHSET, HGET, HGETALLObject/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 TermMongoDB Term
DatabaseDatabase
TableCollection
Row / RecordDocument
ColumnField
Primary Key_id (auto-created)
JOIN$lookup (aggregation)
SchemaNo 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

AspectRedisMongoDBSQL (RDBMS)
Data ModelKey-ValueDocuments (JSON)Tables (rows/cols)
StorageIn-memory (RAM)Disk-basedDisk-based
SpeedFastest (<1ms)FastModerate
SchemaNoneFlexibleFixed/strict
QueryKey lookup onlyRich queriesFull SQL
RelationsNo$lookup / embedJOINs
Best forCache, sessionsContent, catalogsStructured data
ConsistencyEventualConfigurableStrong (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 tableCREATE TABLE t (...)
Add a columnALTER TABLE t ADD COLUMN col TYPE
Remove table entirelyDROP TABLE t
Empty table, keep structureTRUNCATE TABLE t
Filter rowsWHERE condition
Remove duplicatesSELECT DISTINCT
Sort resultsORDER BY col ASC/DESC
Group + countGROUP BY col
Filter groupsHAVING aggregate_condition
Pattern matchLIKE 'A%' or '_r%'
Check for emptyIS NULL / IS NOT NULL
Match listIN ('CS','IT')
Range inclusiveBETWEEN 10 AND 20
Check row existsEXISTS (subquery)
Compare to subquery setANY / ALL

All Facts in One Table

TopicKey Rule
SQL paradigmDeclarative — WHAT not HOW
CHAR vs VARCHARCHAR fixed (faster), VARCHAR variable (saves space)
PK constraintUNIQUE + NOT NULL combined
TRUNCATE vs DELETETRUNCATE = DDL (no rollback); DELETE = DML (rollback ok)
FK ON DELETE CASCADEChild rows deleted when parent deleted
SQL exec orderFROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
INNER JOINOnly rows with matches in BOTH tables
LEFT JOINAll left + matching right (NULL if no right match)
CROSS JOIN rowsm × n (Cartesian product)
WHERE vs HAVINGWHERE = before grouping; HAVING = after aggregation
COUNT(*) vs COUNT(col)COUNT(*) includes NULLs; COUNT(col) ignores NULLs
Correlated subqueryDepends on outer row → runs once per outer row
EXISTSReturns TRUE if subquery has ≥1 row
ViewVirtual table — stored query, no physical data
Trigger NEW/OLDNEW = new values; OLD = old values
NoSQL BASEBasically Available, Soft state, Eventually consistent
CAP theoremChoose max 2 of: Consistency, Availability, Partition Tolerance
Redis storageIn-memory (RAM) → sub-millisecond
MongoDB collection= SQL table. Document = row. Field = column. _id = PK
Horizontal scaleAdd more servers (NoSQL); vertical = bigger server (RDBMS)