Loading...
Loading...
Phase 1: Technical Theory | Date: 28 July 2026 | Subject: SQL Mastery | Expected Questions: Part of 15 DBMS Questions — Highest-Weight Subject
Today you will study:
| Hour | Topic |
|---|---|
| 1 | DDL: CREATE, ALTER, DROP; DML: SELECT, INSERT, UPDATE, DELETE |
| 2 | DCL: GRANT, REVOKE; TCL: COMMIT, ROLLBACK, SAVEPOINT; aggregate functions |
| 3 | WHERE, GROUP BY, HAVING, ORDER BY, DISTINCT, LIKE, IN and BETWEEN |
| 4 | INNER, LEFT, RIGHT, FULL OUTER, CROSS and SELF JOIN; correlated and non-correlated subqueries |
| 5 | Transactions, ACID, transaction states, serializability, locks, 2PL and NoSQL |
After completing this material, you will be able to:
WHERE and HAVING correctly.LIKE.IN, BETWEEN and DISTINCT.SQL stands for Structured Query Language.
It is used to communicate with relational database systems.
SQL can be used to:
SQL is declarative.
A declarative language describes what result is required. The DBMS decides how to obtain that result.
Example:
SELECT Name
FROM Student
WHERE Marks > 80;
The query asks for names of students with marks above 80. It does not specify the exact internal search procedure.
| Category | Full Form | Main Purpose | Commands |
|---|---|---|---|
| DDL | Data Definition Language | Defines database structure | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| DML | Data Manipulation Language | Manipulates table rows | INSERT, UPDATE, DELETE |
| DQL | Data Query Language | Retrieves data | SELECT |
| DCL | Data Control Language | Controls permissions | GRANT, REVOKE |
| TCL | Transaction Control Language | Controls transactions | COMMIT, ROLLBACK, SAVEPOINT |
Many exam books include SELECT under DML. Other books place it separately under DQL. Follow the wording of the question.
DDL = Design
DML = Modify rows
DQL = Query
DCL = Control access
TCL = Transaction control
We will use the following tables.
| DeptID | DeptName | City |
|---|---|---|
| 10 | Computer | Jaipur |
| 20 | Science | Kota |
| 30 | Commerce | Ajmer |
| 40 | Arts | Udaipur |
| StudentID | StudentName | Marks | DeptID |
|---|---|---|---|
| 1 | Asha | 85 | 10 |
| 2 | Ravi | 72 | 20 |
| 3 | Mohan | 85 | 10 |
| 4 | Neha | 60 | 30 |
| 5 | Imran | 45 | NULL |
| 6 | Kavya | 92 | 10 |
CREATE creates a database object.
Objects include:
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL,
City VARCHAR(30)
);
| Part | Meaning |
|---|---|
CREATE TABLE | Creates a table |
Department | Table name |
DeptID INT | Integer column |
PRIMARY KEY | Unique and not NULL |
VARCHAR(50) | Variable-length text up to the allowed length |
NOT NULL | Value is required |
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
StudentName VARCHAR(50) NOT NULL,
Marks DECIMAL(5,2),
DeptID INT,
CONSTRAINT chk_marks
CHECK (Marks BETWEEN 0 AND 100),
CONSTRAINT fk_student_department
FOREIGN KEY (DeptID)
REFERENCES Department(DeptID)
);
A constraint is a rule enforced by the database.
| Constraint | Purpose |
|---|---|
PRIMARY KEY | Uniquely identifies each row |
FOREIGN KEY | References a key in another table |
NOT NULL | Prevents NULL |
UNIQUE | Prevents duplicate non-NULL values according to DBMS rules |
CHECK | Tests a condition |
DEFAULT | Supplies a default value |
Exact names and limits differ among DBMS products.
| Type | Purpose | Example |
|---|---|---|
INT | Whole numbers | 101 |
SMALLINT | Smaller whole numbers | 25 |
DECIMAL(p,s) | Exact decimal | DECIMAL(8,2) |
FLOAT | Approximate numeric value | 3.14 |
CHAR(n) | Fixed-length text | CHAR(10) |
VARCHAR(n) | Variable-length text | VARCHAR(50) |
DATE | Date | 2026-07-28 |
TIME | Time | 10:30:00 |
TIMESTAMP | Date and time | Date-time value |
BOOLEAN | True or false where supported | TRUE |
BLOB | Binary large object | Image or file data |
CLOB | Character large object | Large text |
CHAR vs VARCHARCHAR(n) | VARCHAR(n) |
|---|---|
| Fixed-length character data | Variable-length character data |
| May pad shorter values | Stores varying lengths |
| Useful for fixed codes | Useful for names and addresses |
ALTER changes the structure of an existing table.
ALTER TABLE Student
ADD Email VARCHAR(100);
ALTER TABLE Student
DROP COLUMN Email;
ALTER TABLE Student
ADD CONSTRAINT uq_student_email
UNIQUE (Email);
The exact syntax differs by DBMS.
Examples may use:
ALTER TABLE Student
ALTER COLUMN StudentName VARCHAR(100);
or:
ALTER TABLE Student
MODIFY StudentName VARCHAR(100);
Syntax differs among DBMS products. A common form is:
ALTER TABLE Student
RENAME COLUMN StudentName TO Name;
ALTER changes table structure, not ordinary row values.
DROP removes a database object and its definition.
DROP TABLE Student;
This removes:
Recovery depends on the DBMS, transaction rules and backup facilities.
DROP should be used carefully.
TRUNCATE removes all rows from a table while normally preserving its structure.
TRUNCATE TABLE Student;
General exam characteristics:
WHERE clause| Feature | DELETE | TRUNCATE | DROP |
|---|---|---|---|
| Category | DML | Usually DDL | DDL |
| Removes selected rows | Yes, with WHERE | No | No |
| Removes all rows | Yes, without WHERE | Yes | Yes, with object |
| Keeps table structure | Yes | Yes | No |
WHERE allowed | Yes | No | No |
| Removes table definition | No | No | Yes |
| Transaction behaviour | Usually rollback possible before commit | DBMS-dependent | DBMS-dependent |
DELETE = Remove rows
TRUNCATE = Empty table
DROP = Remove table
INSERT adds new rows.
INSERT INTO Department (DeptID, DeptName, City)
VALUES (10, 'Computer', 'Jaipur');
If values follow the table’s column order:
INSERT INTO Department
VALUES (20, 'Science', 'Kota');
Writing column names is safer and clearer.
Supported syntax in many DBMS products:
INSERT INTO Department (DeptID, DeptName, City)
VALUES
(30, 'Commerce', 'Ajmer'),
(40, 'Arts', 'Udaipur');
INSERT INTO TopStudent (StudentID, StudentName, Marks)
SELECT StudentID, StudentName, Marks
FROM Student
WHERE Marks >= 80;
SELECT retrieves data.
SELECT *
FROM Student;
The asterisk means all columns.
SELECT StudentName, Marks
FROM Student;
An alias gives a temporary display name.
SELECT StudentName AS Name,
Marks AS Score
FROM Student;
AS is optional in many SQL dialects.
SELECT StudentName,
Marks,
Marks + 5 AS RevisedMarks
FROM Student;
This calculates a displayed value. It does not update the stored marks.
SQL string values normally use single quotation marks:
'Asha'
'Jaipur'
Double quotation marks are generally used for quoted identifiers under standard SQL rules, though DBMS settings differ.
UPDATE changes existing rows.
UPDATE Student
SET Marks = 90
WHERE StudentID = 1;
UPDATE Department
SET DeptName = 'Computer Science',
City = 'Jodhpur'
WHERE DeptID = 10;
UPDATE Student
SET Marks = Marks + 5;
This updates every row.
Without WHERE, all rows are updated.
DELETE removes rows.
DELETE FROM Student
WHERE StudentID = 5;
DELETE FROM Student
WHERE Marks < 40;
DELETE FROM Student;
The table structure remains.
Without WHERE, all rows are deleted.
Before running UPDATE or DELETE:
WHERE condition.SELECT.COMMIT or ROLLBACK.Example:
SELECT *
FROM Student
WHERE DeptID = 10;
After confirming:
UPDATE Student
SET Marks = Marks + 2
WHERE DeptID = 10;
GRANT gives privileges to a user or role.
A privilege is permission to perform an operation.
Example:
GRANT SELECT
ON Student
TO teacher_user;
This allows teacher_user to read STUDENT.
GRANT SELECT, INSERT, UPDATE
ON Student
TO clerk_user;
Syntax and meaning vary by DBMS:
GRANT ALL PRIVILEGES
ON Student
TO admin_user;
REVOKE removes previously granted privileges.
REVOKE UPDATE
ON Student
FROM clerk_user;
Now clerk_user cannot update STUDENT through that permission.
| GRANT | REVOKE |
|---|---|
| Gives permission | Removes permission |
| DCL | DCL |
Uses TO | Uses FROM |
A role is a named collection of privileges.
Instead of granting permissions separately to every user:
Conceptual example:
CREATE ROLE teacher_role;
GRANT SELECT
ON Student
TO teacher_role;
Role syntax varies among systems.
A transaction is a logical unit of database work containing one or more operations.
Example bank transfer:
Both steps should succeed together.
COMMIT makes the current transaction’s changes permanent and ends that transaction under normal transaction processing.
UPDATE Account
SET Balance = Balance - 500
WHERE AccountID = 1;
UPDATE Account
SET Balance = Balance + 500
WHERE AccountID = 2;
COMMIT;
After commit, the changes are durable according to the database’s guarantees.
ROLLBACK cancels uncommitted changes in the current transaction.
UPDATE Student
SET Marks = 200
WHERE StudentID = 1;
ROLLBACK;
The invalid uncommitted change is undone.
A normal rollback cannot usually undo a transaction that has already been committed.
Recovery after commit requires other methods, such as backup restoration or compensating transactions.
A savepoint marks a position inside a transaction.
SAVEPOINT point1;
Later, the transaction can roll back to that point.
UPDATE Student
SET Marks = 90
WHERE StudentID = 1;
SAVEPOINT after_first_update;
UPDATE Student
SET Marks = 95
WHERE StudentID = 2;
ROLLBACK TO after_first_update;
COMMIT;
Result:
COMMIT makes the remaining change permanent.Transaction starts
│
v
Operation A
│
v
SAVEPOINT S1
│
v
Operation B
│
v
ROLLBACK TO S1
│
└── Operation B undone
│
v
COMMIT
| Command | Purpose |
|---|---|
COMMIT | Makes transaction changes permanent |
ROLLBACK | Cancels uncommitted transaction changes |
SAVEPOINT | Marks a point within a transaction |
ROLLBACK TO | Returns to a savepoint |
Automatic commit behaviour and DDL transaction handling differ among DBMS products.
An aggregate function calculates one result from multiple rows.
Main aggregate functions:
COUNTSUMAVGMAXMINSELECT COUNT(*)
FROM Student;
If STUDENT has six rows:
6
COUNT(*) counts rows, including rows containing NULL values.
SELECT COUNT(DeptID)
FROM Student;
If one student has DeptID = NULL, the result is:
5
SELECT COUNT(DISTINCT DeptID)
FROM Student;
Non-NULL department values are:
10, 20, 30
Result:
3
SUM adds numeric non-NULL values.
SELECT SUM(Marks)
FROM Student;
Marks:
85 + 72 + 85 + 60 + 45 + 92 = 439
Result:
439
AVG returns the average of numeric non-NULL values.
SELECT AVG(Marks)
FROM Student;
Calculation:
439 / 6 = 73.166...
The displayed precision depends on the DBMS and data type.
If one mark is NULL, AVG(Marks) normally divides by the number of non-NULL marks, not the total row count.
SELECT MAX(Marks), MIN(Marks)
FROM Student;
Result:
MAX = 92
MIN = 45
MAX and MIN can also work with dates and text under the DBMS’s ordering rules.
| Function | Result | Ignores NULL? |
|---|---|---|
COUNT(*) | Number of rows | No; counts rows |
COUNT(column) | Number of non-NULL values | Yes |
COUNT(DISTINCT column) | Distinct non-NULL values | Yes |
SUM(column) | Total | Yes |
AVG(column) | Average | Yes |
MAX(column) | Largest value | Yes |
MIN(column) | Smallest value | Yes |
A common query structure is:
SELECT column_list
FROM table_list
WHERE row_condition
GROUP BY grouping_columns
HAVING group_condition
ORDER BY sorting_columns;
Not every clause is required.
Although SQL is written starting with SELECT, its logical processing is commonly understood in this order:
1. FROM
2. JOIN and ON
3. WHERE
4. GROUP BY
5. HAVING
6. SELECT
7. DISTINCT
8. ORDER BY
Friendly Jaguars Wear Green Hats, Selecting Delicious Oranges
This explains why a select-list alias often cannot be used in WHERE: the WHERE step logically occurs before SELECT.
WHERE filters individual rows before grouping.
SELECT StudentName, Marks
FROM Student
WHERE Marks >= 80;
Result:
| StudentName | Marks |
|---|---|
| Asha | 85 |
| Mohan | 85 |
| Kavya | 92 |
| Operator | Meaning |
|---|---|
= | Equal |
<> or != | Not equal |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
AND | Both conditions must be true |
OR | At least one condition true |
NOT | Reverses a condition |
SELECT *
FROM Student
WHERE Marks >= 70
AND DeptID = 10;
Result:
A common logical precedence is:
NOTANDORUse parentheses to make the intention clear.
WHERE DeptID = 10
OR DeptID = 20
AND Marks >= 80
AND is evaluated before OR.
Clearer version:
WHERE (DeptID = 10 OR DeptID = 20)
AND Marks >= 80
Do not compare NULL using:
DeptID = NULL
Use:
DeptID IS NULL
or:
DeptID IS NOT NULL
SELECT StudentName
FROM Student
WHERE DeptID IS NULL;
Result:
Imran
NULL means unknown or missing. Ordinary equality with unknown does not produce TRUE.
DISTINCT removes duplicate rows from the query result.
SELECT DISTINCT Marks
FROM Student;
Marks in the table:
85, 72, 85, 60, 45, 92
Distinct result:
85, 72, 60, 45, 92
SELECT DISTINCT DeptID, Marks
FROM Student;
DISTINCT applies to the complete selected combination, not separately to each column.
ORDER BY sorts the result.
SELECT StudentName, Marks
FROM Student
ORDER BY Marks ASC;
ASC is commonly the default.
SELECT StudentName, Marks
FROM Student
ORDER BY Marks DESC;
SELECT StudentName, DeptID, Marks
FROM Student
ORDER BY DeptID ASC, Marks DESC;
The result is sorted by department first. Within each department, marks are sorted descending.
Without ORDER BY, row order is not guaranteed.
LIKE performs pattern matching on text.
Main wildcards:
| Wildcard | Meaning |
|---|---|
% | Zero or more characters |
_ | Exactly one character |
WHERE StudentName LIKE 'A%'
Matches:
WHERE StudentName LIKE '%a'
Matches names ending in a.
WHERE StudentName LIKE '%av%'
May match:
Ravi
WHERE StudentName LIKE '____'
Four underscores mean exactly four characters.
WHERE StudentName LIKE '_a%'
Examples:
a, so it does match.s.Case sensitivity depends on the DBMS, collation and operator used.
SELECT StudentName
FROM Student
WHERE StudentName NOT LIKE 'A%';
Returns names that do not begin with A, subject to NULL and collation rules.
IN checks whether a value belongs to a list or subquery result.
SELECT *
FROM Student
WHERE DeptID IN (10, 20);
Equivalent basic condition:
WHERE DeptID = 10
OR DeptID = 20
WHERE DeptID NOT IN (10, 20)
NOT IN can produce unexpected results if the list or subquery contains NULL because SQL uses three-valued logic. NOT EXISTS is often safer for anti-matching queries.
BETWEEN checks an inclusive range.
SELECT StudentName, Marks
FROM Student
WHERE Marks BETWEEN 60 AND 85;
Equivalent:
WHERE Marks >= 60
AND Marks <= 85
Result includes both 60 and 85.
WHERE Marks NOT BETWEEN 60 AND 85
GROUP BY combines rows with the same grouping values.
SELECT DeptID, COUNT(*) AS StudentCount
FROM Student
GROUP BY DeptID;
Possible result:
| DeptID | StudentCount |
|---|---|
| 10 | 3 |
| 20 | 1 |
| 30 | 1 |
| NULL | 1 |
Rows with NULL grouping values normally form one group.
SELECT DeptID,
AVG(Marks) AS AverageMarks,
MAX(Marks) AS HighestMarks
FROM Student
GROUP BY DeptID;
For DeptID 10:
Marks = 85, 85, 92
Average = 262 / 3
Highest = 92
In a grouped query, a selected expression should generally be:
Correct:
SELECT DeptID, AVG(Marks)
FROM Student
GROUP BY DeptID;
Incorrect under standard grouping rules:
SELECT StudentName, DeptID, AVG(Marks)
FROM Student
GROUP BY DeptID;
StudentName is neither grouped nor aggregated.
Some DBMS modes may allow non-standard behaviour, but do not rely on it.
HAVING filters groups after grouping.
SELECT DeptID, COUNT(*) AS StudentCount
FROM Student
GROUP BY DeptID
HAVING COUNT(*) > 1;
Result:
| DeptID | StudentCount |
|---|---|
| 10 | 3 |
| WHERE | HAVING |
|---|---|
| Filters rows | Filters groups |
| Applied before grouping | Applied after grouping |
| Usually does not contain aggregate conditions | Commonly contains aggregate conditions |
| Can be used without GROUP BY | Often used with GROUP BY |
Example: Marks >= 60 | Example: AVG(Marks) >= 70 |
SELECT DeptID, AVG(Marks) AS AverageMarks
FROM Student
WHERE Marks >= 50
GROUP BY DeptID
HAVING AVG(Marks) >= 75;
Processing:
WHERE removes rows with marks below 50.HAVING keeps groups with average at least 75.WHERE filters rows.
HAVING filters groups.
SELECT DeptID,
COUNT(*) AS StudentCount,
AVG(Marks) AS AverageMarks
FROM Student
WHERE Marks >= 50
GROUP BY DeptID
HAVING COUNT(*) >= 2
ORDER BY AverageMarks DESC;
Meaning:
A join combines related rows from two or more tables.
We will use:
| StudentID | StudentName | DeptID |
|---|---|---|
| 1 | Asha | 10 |
| 2 | Ravi | 20 |
| 3 | Mohan | 10 |
| 4 | Neha | 30 |
| 5 | Imran | NULL |
| DeptID | DeptName |
|---|---|
| 10 | Computer |
| 20 | Science |
| 40 | Arts |
Important observations:
An INNER JOIN returns only matching rows.
SELECT s.StudentName,
d.DeptName
FROM Student AS s
INNER JOIN Department AS d
ON s.DeptID = d.DeptID;
Result:
| StudentName | DeptName |
|---|---|
| Asha | Computer |
| Ravi | Science |
| Mohan | Computer |
Not included:
STUDENT matching rows ∩ DEPARTMENT matching rows
An equi join uses equality as the join condition.
ON s.DeptID = d.DeptID
Most common inner joins are equi joins.
A LEFT JOIN returns:
All rows from the left table
Matching rows from the right table
NULL for missing right-side values
SELECT s.StudentName, d.DeptName FROM Student AS s LEFT JOIN Department AS d ON s.DeptID = d.DeptID;
Result:
| StudentName | DeptName |
|---|---|
| Asha | Computer |
| Ravi | Science |
| Mohan | Computer |
| Neha | NULL |
| Imran | NULL |
Arts is not included because it exists only in the right table.
LEFT JOIN = Keep every left row
A RIGHT JOIN returns:
All rows from the right table
Matching rows from the left table
NULL for missing left-side values
SELECT s.StudentName, d.DeptName FROM Student AS s RIGHT JOIN Department AS d ON s.DeptID = d.DeptID;
Result:
| StudentName | DeptName |
|---|---|
| Asha | Computer |
| Mohan | Computer |
| Ravi | Science |
| NULL | Arts |
Neha and Imran are not included because they exist only on the left without a match.
RIGHT JOIN = Keep every right row
Some DBMS products, such as SQLite, historically had limited outer-join support, and query capabilities vary by version. A RIGHT JOIN can often be rewritten by swapping table positions and using LEFT JOIN.
A FULL OUTER JOIN returns:
All matching rows
All unmatched left rows
All unmatched right rows
SELECT s.StudentName, d.DeptName FROM Student AS s FULL OUTER JOIN Department AS d ON s.DeptID = d.DeptID;
Result:
| StudentName | DeptName |
|---|---|
| Asha | Computer |
| Mohan | Computer |
| Ravi | Science |
| Neha | NULL |
| Imran | NULL |
| NULL | Arts |
FULL OUTER JOIN = Keep everything from both sides
Some systems, including MySQL, do not directly support FULL OUTER JOIN. It can often be simulated with a combination of LEFT JOIN, RIGHT JOIN and UNION.
A CROSS JOIN returns the Cartesian product.
Every row of the first table is combined with every row of the second table.
SELECT s.StudentName,
d.DeptName
FROM Student AS s
CROSS JOIN Department AS d;
If:
Student has 5 rows
Department has 3 rows
Result rows:
5 × 3 = 15
CROSS JOIN rows = Left rows × Right rows
Students:
Asha, Ravi
Departments:
Computer, Science
Result:
| StudentName | DeptName |
|---|---|
| Asha | Computer |
| Asha | Science |
| Ravi | Computer |
| Ravi | Science |
A self join joins a table to itself.
It requires table aliases to distinguish the two logical copies.
| EmpID | EmpName | ManagerID |
|---|---|---|
| 1 | Asha | NULL |
| 2 | Ravi | 1 |
| 3 | Mohan | 1 |
| 4 | Neha | 2 |
SELECT e.EmpName AS Employee,
m.EmpName AS Manager
FROM Employee AS e
LEFT JOIN Employee AS m
ON e.ManagerID = m.EmpID;
Result:
| Employee | Manager |
|---|---|
| Asha | NULL |
| Ravi | Asha |
| Mohan | Asha |
| Neha | Ravi |
Both e and m refer to EMPLOYEE, but they represent different roles.
| Join | Result |
|---|---|
| INNER JOIN | Matching rows only |
| LEFT JOIN | All left rows plus matches |
| RIGHT JOIN | All right rows plus matches |
| FULL OUTER JOIN | All rows from both sides |
| CROSS JOIN | Every possible row combination |
| SELF JOIN | A table joined to itself |
INNER = Intersection
LEFT = Keep left
RIGHT = Keep right
FULL = Keep all
CROSS = Multiply rows
SELF = Same table twice
SELECT s.StudentName
FROM Student AS s
LEFT JOIN Department AS d
ON s.DeptID = d.DeptID
WHERE d.DeptID IS NULL;
Result:
SELECT d.DeptName
FROM Department AS d
LEFT JOIN Student AS s
ON d.DeptID = s.DeptID
WHERE s.StudentID IS NULL;
Result:
Arts
This difference is important.
SELECT s.StudentName, d.DeptName
FROM Student AS s
LEFT JOIN Department AS d
ON s.DeptID = d.DeptID
AND d.DeptName = 'Computer';
All students remain because it is a LEFT JOIN. Non-Computer or unmatched right-side values become NULL.
SELECT s.StudentName, d.DeptName
FROM Student AS s
LEFT JOIN Department AS d
ON s.DeptID = d.DeptID
WHERE d.DeptName = 'Computer';
Rows with NULL department names are removed by WHERE.
This makes the result behave like an inner match for that condition.
A subquery is a query written inside another SQL statement.
It is also called:
The surrounding query is called the outer query.
SELECT StudentName, Marks
FROM Student
WHERE Marks > (
SELECT AVG(Marks)
FROM Student
);
The inner query calculates the average.
The outer query returns students scoring above that average.
A non-correlated subquery can execute independently of the outer query.
Example:
SELECT AVG(Marks)
FROM Student;
It does not use a value from the outer query.
SELECT StudentName
FROM Student
WHERE Marks > (
SELECT AVG(Marks)
FROM Student
);
Conceptual process:
A single-row subquery returns one row or one value.
Use operators such as:
=><>=<=<>Example:
SELECT StudentName
FROM Student
WHERE Marks = (
SELECT MAX(Marks)
FROM Student
);
Returns the student or students whose marks equal the maximum.
Even though the subquery returns one value, the outer query may return multiple students if there is a tie.
A multi-row subquery returns several values.
Use operators such as:
INANYALLEXISTSSELECT StudentName
FROM Student
WHERE DeptID IN (
SELECT DeptID
FROM Department
WHERE City IN ('Jaipur', 'Kota')
);
ANY compares a value with at least one value returned by the subquery.
Example:
Marks > ANY (subquery)
Meaning:
Marks is greater than at least one returned value.
If the subquery returns:
60, 70, 80
Then:
Marks > ANY (...)
is true for a mark greater than at least one of them. For ordinary numeric values, this is effectively greater than the minimum, subject to empty sets and NULL rules.
ALL compares a value with every value returned by the subquery.
Example:
Marks > ALL (subquery)
If the subquery returns:
60, 70, 80
the mark must be greater than all values, effectively greater than 80 under ordinary non-NULL conditions.
| Operator | Meaning |
|---|---|
> ANY | Greater than at least one returned value |
> ALL | Greater than every returned value |
= ANY | Similar to IN |
< ALL | Less than every returned value |
EXISTS is true if a subquery returns at least one row.
SELECT d.DeptName
FROM Department AS d
WHERE EXISTS (
SELECT 1
FROM Student AS s
WHERE s.DeptID = d.DeptID
);
The subquery is correlated because it refers to d.DeptID.
NOT EXISTS is true if the subquery returns no rows.
SELECT d.DeptName
FROM Department AS d
WHERE NOT EXISTS (
SELECT 1
FROM Student AS s
WHERE s.DeptID = d.DeptID
);
Result:
Arts
A correlated subquery refers to a column from the outer query.
It cannot be evaluated independently in the same way as a non-correlated subquery.
SELECT s.StudentName,
s.Marks,
s.DeptID
FROM Student AS s
WHERE s.Marks > (
SELECT AVG(s2.Marks)
FROM Student AS s2
WHERE s2.DeptID = s.DeptID
);
The inner query uses:
s.DeptID
from the outer row.
For each outer student:
Modern query optimizers may transform the execution, but this is the correct logical understanding.
| Non-Correlated | Correlated |
|---|---|
| Independent of outer query | Refers to outer-query columns |
| Can run by itself | Depends on the outer row |
| Conceptually runs once | Conceptually evaluated for outer rows |
| Usually simpler | Often more expensive |
| Example: compare with overall average | Example: compare with department average |
| JOIN | Subquery |
|---|---|
| Combines tables in one table expression | Places one query inside another |
| Often used to retrieve columns from related tables | Often used for filtering or calculated comparisons |
| May be clearer for direct relationships | May be clearer for existence or aggregate tests |
| Optimizer may produce similar plans | Optimizer may transform into a join |
There is no universal rule that one is always faster. Performance depends on:
A transaction is a sequence of database operations treated as one logical unit.
Example bank transfer:
Read
Account A balance
│
v
Subtract ₹500 from Account A
│
v
Read Account B balance
│
v
Add ₹500 to Account B
│
v
Commit both changes
The two balance changes form one transaction.
If the first update succeeds but the second fails, the complete transfer should be rolled back. Otherwise, money would disappear from one account without reaching the other.
A transaction has:
COMMIT, orROLLBACKConceptual example:
BEGIN TRANSACTION;
UPDATE Account
SET Balance = Balance - 500
WHERE AccountID = 1;
UPDATE Account
SET Balance = Balance + 500
WHERE AccountID = 2;
COMMIT;
The exact command used to begin a transaction differs among DBMS products.
Common forms include:
BEGIN;
BEGIN TRANSACTION;
START TRANSACTION;
Transaction theory often uses two basic operations.
read(X)
This reads data item X from the database into the transaction’s local memory.
write(X)
This writes the transaction’s updated value of X back to the database.
A transaction adds 100 to balance X:
read(X)
X = X + 100
write(X)
ACID describes four important transaction properties:
ACID
Atomicity means a transaction is treated as one indivisible unit.
Either:
Transaction:
If step 2 fails, step 1 must also be undone.
Transaction operations
│
├── All successful ───> COMMIT
│
└── Any failure ──────> ROLLBACK
Atomicity = All or nothing
Consistency means a transaction moves the database from one valid state to another valid state while preserving defined rules.
Examples of rules:
Before transfer:
Account A = ₹2,000
Account B = ₹1,000
Total = ₹3,000
After transferring ₹500:
Account A = ₹1,500
Account B = ₹1,500
Total = ₹3,000
The total remains consistent.
The DBMS enforces declared constraints, while correct transaction logic is also the application programmer’s responsibility.
Isolation means concurrent transactions should not interfere in a way that produces an incorrect result.
Each transaction should behave as if it were executing alone, according to the selected isolation level.
Two users update the same bank balance at the same time.
Without isolation, one user’s change may overwrite the other’s change.
Isolation is supported through techniques such as:
MVCC stands for Multiversion Concurrency Control. It keeps multiple versions of data to help transactions read consistent versions.
Isolation = Concurrent transactions appear independent
Durability means that once a transaction commits, its changes survive later failures.
After commit, data should remain available even if:
Durability may use:
Durability = Committed data survives
| Property | Meaning | Failure Prevented |
|---|---|---|
| Atomicity | All operations or none | Partial transaction |
| Consistency | Valid state to valid state | Rule violations |
| Isolation | Concurrent transactions do not improperly interfere | Incorrect concurrent results |
| Durability | Committed changes survive | Loss after commit |
| Transfer Requirement | ACID Property |
|---|---|
| Both debit and credit happen together | Atomicity |
| Total money remains valid | Consistency |
| Other transfers do not interfere incorrectly | Isolation |
| Completed transfer survives a crash | Durability |
A transaction may move through these states:
The transaction is executing its operations.
Examples:
Reading rows
Performing calculations
Updating rows
Start → Active
The final statement has executed, but the system has not yet guaranteed that the transaction’s effects are permanently recorded.
Active → Final operation completed → Partially committed
A failure can still occur before complete commit processing finishes.
The transaction has completed successfully, and its changes are durable.
Partially committed → Committed
The transaction cannot continue.
Possible causes:
Constraint violation
Deadlock victim selection
Hardware failure
Software error
Invalid input
Explicit cancellation
Active or partially committed → Failed
After failure, the transaction’s changes are rolled back.
The database is restored to the state before that transaction began, as required by atomicity.
From aborted state, the transaction may:
After commit or abort processing is complete, the transaction leaves the system.
┌─────────┐
│ Active │
└────┬────┘
│ Final statement executed
v
┌─────────────────────┐
│ Partially Committed │
└──────┬──────────────┘
│ Commit succeeds
v
┌───────────┐
│ Committed │
└─────┬─────┘
│
v
┌────────────┐
│ Terminated │
└────────────┘
Failure path:
Active or Partially Committed
│
v
┌────────┐
│ Failed │
└───┬────┘
│ Rollback
v
┌─────────┐
│ Aborted │
└────┬────┘
│
┌────┴─────┐
│ │
v v
Restart Terminated
A schedule is the order in which operations from one or more transactions are executed.
Suppose:
Transaction T1:
read(X)
X = X + 10
write(X)
Transaction T2:
read(X)
X = X * 2
write(X)
A schedule decides how T1 and T2 operations are ordered.
A serial schedule completes one transaction before starting another.
T1: read(X)
T1: write(X)
T1: commit
T2: read(X)
T2: write(X)
T2: commit
No interleaving occurs.
A non-serial schedule interleaves operations from multiple transactions.
Example:
T1: read(X)
T2: read(Y)
T1: write(X)
T2: write(Y)
T1: commit
T2: commit
Interleaving can improve performance, but it must preserve correctness.
A serializable schedule is a non-serial schedule whose effect is equivalent to some serial schedule.
It provides concurrency while preserving the correctness of serial execution.
Every serial schedule is serializable.
But:
A serializable schedule does not have to be serial.
The main theoretical types are:
Conflict serializability is more commonly tested.
Two operations conflict if:
| Operation Pair on Same Item | Conflict? |
|---|---|
| Read–Read | No |
| Read–Write | Yes |
| Write–Read | Yes |
| Write–Write | Yes |
Different transactions
+ Same item
+ At least one write
= Conflict
Two schedules are conflict equivalent if:
A schedule is conflict serializable if it is conflict equivalent to a serial schedule.
A precedence graph, also called a serialization graph, is used to test conflict serializability.
Create one node for each transaction.
Find conflicting operations.
If an operation of Ti occurs before a conflicting operation of Tj, draw:
Ti → Tj
Check for a cycle.
Schedule:
r1(X)
w1(X)
r2(X)
w2(X)
Conflicts place T1 before T2.
Graph:
T1 ───> T2
There is no cycle.
Therefore, the schedule is conflict serializable.
Equivalent serial order:
T1, then T2
Schedule:
r1(X)
w1(X)
r2(X)
w2(Y)
r1(Y)
Conflicts:
On X, T1’s write occurs before T2’s read:
T1 → T2
On Y, T2’s write occurs before T1’s read:
T2 → T1
Graph:
T1 ───> T2
^ │
└───────┘
A cycle exists.
Therefore, the schedule is not conflict serializable.
A lost update occurs when one transaction’s update is overwritten by another transaction.
Initial balance:
X = 1000
Transactions:
T1 adds 100
T2 subtracts 50
Problem schedule:
T1 reads X = 1000
T2 reads X = 1000
T1 calculates 1100
T2 calculates 950
T1 writes 1100
T2 writes 950
Final value:
950
Correct serial result should be:
1000 + 100 - 50 = 1050
T1’s update is lost.
A dirty read occurs when one transaction reads data written by another transaction that has not committed.
Example:
T1 writes Balance = 500
T2 reads Balance = 500
T1 rolls back
T2 used a value that never became permanent.
Dirty read is also called:
A non-repeatable read occurs when a transaction reads the same row twice and gets different values because another transaction committed an update between the reads.
Example:
T1 reads Marks = 80
T2 updates Marks = 90 and commits
T1 reads Marks again = 90
The same row produced two different values inside T1.
A phantom read occurs when repeating a query returns a different set of rows because another transaction inserted or deleted matching rows.
Example:
T1 executes:
SELECT COUNT(*)
FROM Student
WHERE Marks >= 80;
Result:
5
T2 inserts a student with Marks 90 and commits.
T1 runs the same query again:
Result = 6
The additional matching row is a phantom.
An incorrect summary occurs when one transaction calculates an aggregate while another transaction updates some of the same data.
The summary may combine old and new values.
Example:
| Problem | Meaning |
|---|---|
| Lost update | One update overwrites another |
| Dirty read | Reads uncommitted data |
| Non-repeatable read | Same row gives different committed values |
| Phantom read | Repeated query returns a different row set |
| Incorrect summary | Aggregate mixes inconsistent versions |
A lock is a control mechanism that restricts concurrent access to a database item.
Before reading or writing a data item, a transaction may need to obtain a suitable lock.
Locks help maintain:
A binary lock has two states:
It is simple but does not distinguish reading from writing.
A shared lock, also called an S-lock or read lock, is used for reading.
Several transactions may usually hold shared locks on the same item at the same time.
Example:
T1 holds S-lock on X.
T2 may also receive S-lock on X.
Both transactions can read X.
An exclusive lock, also called an X-lock or write lock, is used for writing.
When one transaction holds an X-lock:
Example:
T1 holds X-lock on X.
T2 must wait before reading or writing X.
| Existing Lock | Requested S-lock | Requested X-lock |
|---|---|---|
| S-lock | Compatible | Not compatible |
| X-lock | Not compatible | Not compatible |
Read + Read = Allowed
Read + Write = Wait
Write + Read = Wait
Write + Write = Wait
Granularity means the size of the data item being locked.
Possible levels:
Example:
Table lock
Advantages:
Disadvantages:
Example:
Row lock
Advantages:
Disadvantages:
A transaction may change:
S-lock → X-lock
when it needs to update an item it previously read.
A transaction may change:
X-lock → S-lock
when it no longer needs write access.
Lock conversion must follow the concurrency-control protocol.
2PL stands for Two-Phase Locking.
A transaction following 2PL has two phases:
During the growing phase:
The transaction may acquire locks.
The transaction may upgrade locks.
It cannot release locks.
Acquire locks Acquire more locks Upgrade if permitted No unlock
The lock point is the moment when a transaction obtains its final lock.
After the lock point, it enters the shrinking phase.
During the shrinking phase:
The transaction may release locks.
The transaction may downgrade locks.
It cannot acquire new locks.
Release locks Release more locks No new lock
Transaction begins
│
v
┌───────────────────┐
│ Growing Phase │
│ Acquire locks │
│ No release │
└─────────┬─────────┘
│ Lock point
v
┌───────────────────┐
│ Shrinking Phase │
│ Release locks │
│ No new lock │
└─────────┬─────────┘
│
v
Transaction ends
Basic 2PL guarantees conflict serializability when followed correctly.
Basic 2PL can still cause:
lock-S(A)
read(A)
lock-X(B)
write(B)
unlock(A)
unlock(B)
Phases:
Growing:
lock-S(A)
lock-X(B)
Shrinking:
unlock(A)
unlock(B)
After the first unlock, no new lock is acquired.
Therefore, this follows 2PL.
lock-S(A)
read(A)
unlock(A)
lock-X(B)
write(B)
After releasing A, the transaction acquires a new lock on B.
This violates 2PL because it returns to lock acquisition after shrinking began.
Follows growing and shrinking phases.
Guarantees conflict serializability.
May allow deadlocks and cascading rollbacks.
The transaction obtains all required locks before it begins.
If all locks are not available, it waits without acquiring them.
Advantages:
Limitations:
All exclusive locks are held until the transaction commits or aborts.
Advantages:
All shared and exclusive locks are held until commit or abort.
It is stricter than strict 2PL.
| Type | Main Rule |
|---|---|
| Basic 2PL | Acquire first, then release; no new locks after first release |
| Conservative 2PL | Obtain all locks before execution |
| Strict 2PL | Hold all X-locks until commit or abort |
| Rigorous 2PL | Hold all S-locks and X-locks until commit or abort |
A deadlock occurs when transactions wait for one another indefinitely.
T1 locks A.
T2 locks B.
T1 requests B and waits for T2.
T2 requests A and waits for T1.
Wait cycle:
T1 waits for T2
^ │
│ v
└─────── T2
Neither can continue.
2PL can guarantee conflict serializability, but basic and strict 2PL do not automatically eliminate deadlocks.
Common methods:
A wait-for graph can be used.
The DBMS may:
A cascading rollback occurs when one transaction’s failure forces other transactions to roll back because they read its uncommitted data.
Example:
T1 writes X.
T2 reads uncommitted X.
T1 aborts.
T2 must also abort.
Strict 2PL helps prevent this problem by holding exclusive locks until commit or abort.
A schedule is recoverable if a transaction commits only after the transaction whose data it read has committed.
If T2 reads a value written by T1:
T1 must commit before T2 commits.
A cascadeless schedule allows a transaction to read a value only after the transaction that wrote it has committed.
This prevents cascading rollback.
In a strict schedule, no transaction may read or write a data item written by an uncommitted transaction.
Strict schedules simplify recovery.
A commonly taught relationship is:
Strict
↓
Cascadeless
↓
Recoverable
A strict schedule is cascadeless, and a cascadeless schedule is recoverable.
NoSQL commonly means Not Only SQL.
NoSQL databases are non-relational or not strictly table-centered database systems designed for needs such as:
NoSQL does not mean that SQL is always completely absent. Some NoSQL products provide SQL-like query languages.
NoSQL may be useful when an application needs:
Add more machines to share the workload.
Server 1 + Server 2 + Server 3
Increase the power of one machine.
More CPU
More RAM
Faster storage
NoSQL systems are often designed with horizontal scaling in mind, although relational systems can also scale horizontally.
The four commonly taught types are:
The roadmap specifically emphasizes:
A key-value database stores each value using a unique key.
Key Value
-------- -------------------
user:101 → "Asha"
cart:501 → Product list
session:X → Session information
Key ───> Value
DynamoDB can also support document-like structures.
A document database stores records as documents.
Documents are commonly represented in JSON-like or BSON formats.
{
"studentId": 101,
"name": "Asha",
"marks": 85,
"skills": ["Python", "SQL"],
"address": {
"city": "Jaipur",
"state": "Rajasthan"
}
}
A wide-column database organizes data using row keys and column families.
Different rows may contain different columns.
Row Key: Student101
Personal:Name = Asha
Academic:Marks = 85
Contact:City = Jaipur
A graph database stores:
Represents an entity.
Examples:
Represents a relationship.
Examples:
Stores information about a node or edge.
(Asha)
│ FRIEND_OF
v
(Ravi)
│ PURCHASED
v
(Laptop)
| Type | Structure | Best For | Example |
|---|---|---|---|
| Key-value | Key → Value | Cache, sessions | Redis |
| Document | JSON-like documents | Flexible application data | MongoDB |
| Wide-column | Column families | Large distributed data | Cassandra |
| Graph | Nodes and edges | Relationship-heavy data | Neo4j |
KDWG
Memory sentence:
Keys Describe Wide Graphs
| Basis | SQL Database | NoSQL Database |
|---|---|---|
| Main Model | Relational tables | Key-value, document, column or graph |
| Schema | Usually predefined and structured | Often flexible |
| Relationships | Foreign keys and joins | Embedded data or model-specific links |
| Query Language | SQL | Product-specific APIs or query languages |
| Normalization | Common | Denormalization is common |
| Transactions | Strong ACID support is traditional | Product-dependent; many now support transactions |
| Scaling | Traditionally vertical, also horizontal options | Often designed for horizontal scaling |
| Best Use | Structured data and complex relational queries | Flexible, distributed or specialized data |
| Examples | PostgreSQL, Oracle, MySQL | MongoDB, Redis, Cassandra, Neo4j |
| SQL Limitations | NoSQL Limitations |
|---|---|
| Schema changes may require planning | Less standardization across products |
| Object-to-table mapping may be complex | Joins may be limited or model-specific |
| Distributed scaling can be complex | Data duplication may be common |
| Less natural for some graph operations | Consistency guarantees vary |
| Nested data may require several tables | Product-specific knowledge required |
Examples:
Examples:
No database type is always better.
The correct choice depends on:
The CAP theorem discusses distributed systems.
It focuses on:
All clients see a consistent view according to the system’s consistency model.
Every request receives a non-error response, though it may not contain the newest data under some models.
The system continues operating despite communication failures between network groups.
During a network partition, a distributed system cannot simultaneously guarantee both perfect consistency and full availability in the strict CAP sense.
Do not confuse CAP consistency with ACID consistency. They use the same word in different contexts.
| Category | Purpose | Commands |
|---|---|---|
| DDL | Defines structure | CREATE, ALTER, DROP, TRUNCATE |
| DML | Changes rows | INSERT, UPDATE, DELETE |
| DQL | Retrieves rows | SELECT |
| DCL | Controls permissions | GRANT, REVOKE |
| TCL | Controls transactions | COMMIT, ROLLBACK, SAVEPOINT |
Mnemonic:
DDL = Design
DML = Modify
DQL = Query
DCL = Control
TCL = Transaction
| Command | Removes | Structure Remains? | WHERE? |
|---|---|---|---|
| DELETE | Selected or all rows | Yes | Yes |
| TRUNCATE | All rows | Yes | No |
| DROP | Complete object | No | No |
| Function | Purpose |
|---|---|
| COUNT(*) | Counts rows |
| COUNT(column) | Counts non-NULL values |
| SUM | Total |
| AVG | Average of non-NULL values |
| MAX | Highest |
| MIN | Lowest |
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
Logical order:
FROM
JOIN
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
WHERE = Filters rows before grouping
HAVING = Filters groups after grouping
| Operator | Meaning |
|---|---|
% in LIKE | Zero or more characters |
_ in LIKE | Exactly one character |
| IN | Matches a list or subquery result |
| BETWEEN | Inclusive range |
| IS NULL | Tests NULL |
| DISTINCT | Removes duplicate result rows |
| Join | Keeps |
|---|---|
| INNER | Matching rows |
| LEFT | Every left row |
| RIGHT | Every right row |
| FULL OUTER | Every row from both tables |
| CROSS | Every combination |
| SELF | Same table joined to itself |
Formula:
CROSS JOIN rows = Left rows × Right rows
| Type | Meaning |
|---|---|
| Non-correlated | Independent of outer query |
| Correlated | Uses outer-query value |
| Single-row | Returns one row/value |
| Multi-row | Returns multiple values |
| EXISTS | True if at least one row exists |
| NOT EXISTS | True if no row exists |
| Property | Memory Rule |
|---|---|
| Atomicity | All or nothing |
| Consistency | Correct state |
| Isolation | Independent concurrent execution |
| Durability | Committed data survives |
Active
│
v
Partially committed
│
v
Committed
│
v
Terminated
Failure path:
Active → Failed → Aborted → Restart or Terminated
Serial schedule:
One complete transaction at a time
Serializable schedule:
Same effect as some serial order
Conflict:
Different transactions
+ Same data item
+ At least one write
Precedence graph:
No cycle = Conflict serializable
Cycle = Not conflict serializable
| Lock | Purpose | Compatibility |
|---|---|---|
| Shared or S-lock | Read | Compatible with other S-locks |
| Exclusive or X-lock | Write | Not compatible with S or X |
Growing:
Acquire locks; release none
Lock point:
Final lock acquired
Shrinking:
Release locks; acquire none
Types:
| Type | Rule |
|---|---|
| Basic | Growing then shrinking |
| Conservative | Obtain all locks before execution |
| Strict | Hold X-locks until commit/abort |
| Rigorous | Hold S and X locks until commit/abort |
| Type | Structure | Example |
|---|---|---|
| Key-value | Key → Value | Redis |
| Document | JSON-like documents | MongoDB |
| Wide-column | Column families | Cassandra |
| Graph | Nodes and edges | Neo4j |
Which command changes the structure of an existing table?
A. UPDATE
B. ALTER
C. INSERT
D. COMMIT
Which command removes a table’s definition and data?
A. DELETE
B. TRUNCATE
C. DROP
D. ROLLBACK
What happens if this statement is executed without a WHERE clause?
UPDATE Student
SET Marks = 100;
A. Only the first row is updated
B. Every row is updated
C. The table is dropped
D. No row is updated
Which command gives a user permission?
A. REVOKE
B. GRANT
C. ROLLBACK
D. SAVEPOINT
Which command permanently accepts the current transaction’s changes?
A. COMMIT
B. DELETE
C. DROP
D. REVOKE
Which expression counts every row, regardless of NULL values in particular columns?
A. COUNT(column)
B. COUNT(*)
C. SUM(*)
D. AVG(*)
Which clause filters rows before grouping?
A. HAVING
B. ORDER BY
C. WHERE
D. DISTINCT
Which clause filters groups after aggregate calculation?
A. WHERE
B. HAVING
C. FROM
D. DISTINCT
What does this condition include?
Marks BETWEEN 60 AND 80
A. Values above 60 and below 80 only
B. Values from 60 to 80, including both boundaries
C. Only 60 and 80
D. Values below 60 or above 80
Which pattern matches names whose second character is a?
A. 'a%'
B. '%a'
C. '_a%'
D. '%a%'
Use these row counts for Question 11:
Table A has 4 rows.
Table B has 3 rows.
How many rows does A CROSS JOIN B return?
A. 1
B. 7
C. 12
D. 43
Which join returns all rows from the left table and matching rows from the right table?
A. INNER JOIN
B. LEFT JOIN
C. RIGHT JOIN
D. CROSS JOIN
Which join is used when an EMPLOYEE table is joined to itself to find managers?
A. CROSS JOIN only
B. FULL JOIN only
C. SELF JOIN
D. Natural deletion
A subquery that refers to a column from the outer query is:
A. A correlated subquery
B. A DDL command
C. A view only
D. A transaction log
Which operator is true when a subquery returns at least one row?
A. BETWEEN
B. EXISTS
C. DISTINCT
D. DROP
Which ACID property means all operations of a transaction occur or none occur?
A. Atomicity
B. Consistency
C. Isolation
D. Durability
Which ACID property means committed changes survive a system restart?
A. Atomicity
B. Consistency
C. Isolation
D. Durability
A transaction reads data written by another transaction that has not committed. This is:
A. Phantom read
B. Dirty read
C. Serial schedule
D. Durability
Which pair of locks can normally be held by two transactions on the same item at the same time?
A. X and X
B. S and X
C. S and S
D. X and S
Under basic 2PL, after a transaction releases its first lock, it:
A. May acquire any number of new locks
B. Cannot acquire a new lock
C. Must drop the table
D. Must become a DBA
A precedence graph has no cycle. The schedule is:
A. Not executable
B. Conflict serializable
C. Always deadlocked
D. A dirty read
Which 2PL version holds all exclusive locks until commit or abort?
A. Basic 2PL only
B. Conservative 2PL
C. Strict 2PL
D. No-lock protocol
Which NoSQL type stores data as a key and an associated value?
A. Graph
B. Key-value
C. Relational-only
D. Hierarchical file
Which database type is best suited to highly connected data such as social-network relationships?
A. Graph database
B. Key-value cache only
C. Flat text file
D. Spreadsheet only
Which statement correctly compares SQL and NoSQL?
A. SQL databases cannot support transactions.
B. NoSQL always means no query language.
C. SQL commonly uses relational tables, while NoSQL includes document, key-value and graph models.
D. NoSQL databases never support consistency.
| Q. | Answer | Q. | Answer | Q. | Answer | Q. | Answer | Q. | Answer |
|---|---|---|---|---|---|---|---|---|---|
| 1 | B | 6 | B | 11 | C | 16 | A | 21 | B |
| 2 | C | 7 | C | 12 | B | 17 | D | 22 | C |
| 3 | B | 8 | B | 13 | C | 18 | B | 23 | B |
| 4 | B | 9 | B | 14 | A | 19 | C | 24 | A |
| 5 | A | 10 | C | 15 | B | 20 | B | 25 | C |
ALTER changes the structure of an existing table.
Example:
ALTER TABLE Student
ADD Email VARCHAR(100);
UPDATE changes row values, not the table definition.
DROP TABLE removes:
Table data
Table structure
Table definition
DROP TABLE Student;
TRUNCATE removes all rows but keeps the table structure.
Without a WHERE clause:
UPDATE Student
SET Marks = 100;
changes Marks to 100 in every row.
Always test the intended condition using SELECT before a major update.
GRANT gives privileges.
Example:
GRANT SELECT
ON Student
TO teacher_user;
REVOKE removes privileges.
COMMIT accepts and makes the current transaction’s changes permanent according to the DBMS’s transaction guarantees.
ROLLBACK cancels uncommitted changes.
COUNT(*) counts rows.
COUNT(column) counts only non-NULL values in that column.
Example:
Five rows, one NULL DeptID
COUNT(*) = 5
COUNT(DeptID) = 4
WHERE filters individual rows before grouping.
Example:
WHERE Marks >= 60
HAVING filters groups after GROUP BY.
Example:
GROUP BY DeptID
HAVING AVG(Marks) >= 75
Memory rule:
WHERE → Rows
HAVING → Groups
BETWEEN is inclusive.
Marks BETWEEN 60 AND 80
means:
Marks >= 60
AND Marks <= 80
'_a%'In a LIKE pattern:
_ = Exactly one character
% = Zero or more characters
Therefore:
'_a%'
means:
a as the second characterCROSS JOIN formula:
Left rows × Right rows
Calculation:
4 × 3 = 12
A LEFT JOIN keeps:
A self join treats one table as two logical copies.
Example:
Employee AS e
Employee AS m
One copy represents employees, and the other represents managers.
A correlated subquery uses a value from the current outer-query row.
Example:
WHERE s.Marks > (
SELECT AVG(s2.Marks)
FROM Student AS s2
WHERE s2.DeptID = s.DeptID
);
The inner query refers to outer alias s.
EXISTS is true if its subquery returns at least one row.
NOT EXISTS is true if the subquery returns no rows.
Atomicity means:
All operations happen, or none happen.
It prevents a transaction from remaining partly completed.
Durability means committed changes survive later system failures.
It is supported through mechanisms such as transaction logs and recovery processing.
A dirty read uses data written by an uncommitted transaction.
If the writer rolls back, the reader used a value that never became permanent.
Shared locks are read locks.
Multiple transactions can normally hold S-locks on the same item.
An exclusive lock is incompatible with both shared and exclusive locks.
Under 2PL:
Growing phase:
Acquire locks
Release none
Shrinking phase:
Release locks
Acquire none
The first unlock begins the shrinking phase.
Precedence graph rule:
No cycle → Conflict serializable
Cycle → Not conflict serializable
A topological ordering of the graph gives an equivalent serial order.
Strict 2PL holds all exclusive locks until commit or abort.
This helps:
A key-value database stores:
Key → Value
Example:
session:101 → Session data
Redis is a common example.
Graph databases store:
They are suitable for:
Neo4j is a common example.
SQL databases commonly use:
Tables, rows, columns, keys and joins
NoSQL database models include:
Key-value
Document
Wide-column
Graph
Modern SQL and NoSQL systems can both support important transaction and consistency features. Exact guarantees depend on the product and configuration.
Classify each command:
| Command | Category |
|---|---|
| CREATE | DDL |
| ALTER | DDL |
| DROP | DDL |
| TRUNCATE | Usually DDL |
| INSERT | DML |
| UPDATE | DML |
| DELETE | DML |
| SELECT | DQL or DML in some classifications |
| GRANT | DCL |
| REVOKE | DCL |
| COMMIT | TCL |
| ROLLBACK | TCL |
| SAVEPOINT | TCL |
Requirement:
Create a COURSE table with:
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100) NOT NULL,
Fee DECIMAL(10,2),
DeptID INT,
CONSTRAINT chk_course_fee
CHECK (Fee BETWEEN 0 AND 100000),
CONSTRAINT fk_course_department
FOREIGN KEY (DeptID)
REFERENCES Department(DeptID)
);
INSERT INTO Course (
CourseID,
CourseName,
Fee,
DeptID
)
VALUES (
101,
'Database Systems',
5000,
10
);
Increase the fee by 10%:
UPDATE Course
SET Fee = Fee * 1.10
WHERE CourseID = 101;
DELETE FROM Course
WHERE CourseID = 101;
Marks:
80, 90, NULL, 70, 90
Find:
COUNT(*)
COUNT(Marks)
SUM(Marks)
AVG(Marks)
MAX(Marks)
MIN(Marks)
COUNT(DISTINCT Marks)
Total rows:
COUNT(*) = 5
Non-NULL marks:
80, 90, 70, 90
Therefore:
COUNT(Marks) = 4
Sum:
80 + 90 + 70 + 90 = 330
Average:
330 / 4 = 82.5
Maximum:
90
Minimum:
70
Distinct non-NULL values:
80, 90, 70
Therefore:
COUNT(DISTINCT Marks) = 3
Requirement:
SELECT DeptID,
AVG(Marks) AS AverageMarks
FROM Student
WHERE Marks >= 50
GROUP BY DeptID
HAVING AVG(Marks) > 75;
Explanation:
WHERE Marks >= 50
→ Filters rows
GROUP BY DeptID
→ Creates department groups
HAVING AVG(Marks) > 75
→ Filters groups
| Requirement | Pattern |
|---|---|
| Starts with A | 'A%' |
| Ends with a | '%a' |
Contains av | '%av%' |
| Exactly four characters | '____' |
| Second character is a | '_a%' |
| Starts with A and has exactly four characters | 'A___' |
Tables:
A
| ID | Name |
|---|---|
| 1 | Asha |
| 2 | Ravi |
| 3 | Mohan |
B
| ID | City |
|---|---|
| 1 | Jaipur |
| 3 | Kota |
| 4 | Ajmer |
SELECT A.ID, A.Name, B.City
FROM A
INNER JOIN B
ON A.ID = B.ID;
Result:
| ID | Name | City |
|---|---|---|
| 1 | Asha | Jaipur |
| 3 | Mohan | Kota |
Result:
| ID | Name | City |
|---|---|---|
| 1 | Asha | Jaipur |
| 2 | Ravi | NULL |
| 3 | Mohan | Kota |
Result:
| ID from A | Name | ID from B | City |
|---|---|---|---|
| 1 | Asha | 1 | Jaipur |
| 3 | Mohan | 3 | Kota |
| NULL | NULL | 4 | Ajmer |
Result contains IDs:
1, 2, 3, 4
Tables:
STUDENT has 6 rows.
COURSE has 5 rows.
Result:
6 × 5 = 30 rows
Write a query to find students with marks above the overall average.
SELECT StudentName, Marks
FROM Student
WHERE Marks > (
SELECT AVG(Marks)
FROM Student
);
The inner query is independent of the outer row.
Write a query to find students scoring above their own department’s average.
SELECT s.StudentName,
s.Marks,
s.DeptID
FROM Student AS s
WHERE s.Marks > (
SELECT AVG(s2.Marks)
FROM Student AS s2
WHERE s2.DeptID = s.DeptID
);
The inner query uses the outer student’s DeptID.
BEGIN TRANSACTION;
UPDATE Account
SET Balance = Balance - 500
WHERE AccountID = 1;
SAVEPOINT after_debit;
UPDATE Account
SET Balance = Balance + 500
WHERE AccountID = 2;
ROLLBACK TO after_debit;
COMMIT;
This would be incorrect bank-transfer logic because only the debit remains.
A real transfer should normally roll back the complete transaction if the credit fails.
| Situation | Property |
|---|---|
| Debit and credit both occur or neither occurs | Atomicity |
| Database rules remain valid | Consistency |
| Concurrent transactions do not interfere incorrectly | Isolation |
| Committed transfer survives a crash | Durability |
T2 reads a value written by uncommitted T1.
Answer:
Dirty read
T1 reads the same row twice and receives different committed values.
Answer:
Non-repeatable read
T1 repeats a query and finds additional matching rows.
Answer:
Phantom read
T2 overwrites T1’s update.
Answer:
Lost update
Complete the table:
| Existing | Requested S | Requested X |
|---|---|---|
| S | Yes | No |
| X | No | No |
Memory rule:
Only S with S is compatible.
Schedule:
lock-S(A)
read(A)
lock-X(B)
write(B)
unlock(A)
lock-S(C)
Is it valid under 2PL?
No.
After:
unlock(A)
the shrinking phase begins.
The transaction then tries to acquire:
lock-S(C)
A new lock cannot be acquired during the shrinking phase.
Schedule conflicts produce:
T1 → T2
T2 → T3
T1 → T3
Is the schedule conflict serializable?
Yes.
Graph:
T1 ───> T2 ───> T3
└────────────> T3
There is no cycle.
Equivalent serial order:
T1, T2, T3
Edges:
T1 → T2
T2 → T3
T3 → T1
The graph contains a cycle:
T1 → T2 → T3 → T1
Therefore:
The schedule is not conflict serializable.
| Requirement | Best Basic Type |
|---|---|
| Session data accessed through a unique key | Key-value |
| Flexible nested product records | Document |
| Social-network relationships | Graph |
| Large distributed column-family data | Wide-column |
% and _ mean in LIKE?Use your score from the 25 MCQs.
| Correct Answers | Level | Required Action |
|---|---|---|
| 23–25 | Excellent | Revise the Quick Revision Sheet tomorrow |
| 20–22 | Good | Review incorrect answers once |
| 16–19 | Developing | Repeat joins, clauses and transactions |
| 10–15 | Weak | Restudy all five hourly topics |
| 0–9 | Beginning | Read the material again slowly |
| Questions Missed | Topic to Revise |
|---|---|
| 1–5 | DDL, DML, DCL and TCL |
| 6–10 | Aggregate functions and query clauses |
| 11–15 | Joins and subqueries |
| 16–20 | ACID, anomalies, locks and 2PL |
| 21–25 | Serializability and NoSQL |
Study:
Write from memory:
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
StudentName VARCHAR(50) NOT NULL,
Marks DECIMAL(5,2)
);
Practice:
Study:
Practice:
Study:
Memorize:
WHERE = Rows
HAVING = Groups
Practice:
Study:
Draw two small tables and manually produce every join result.
Memorize:
INNER = Matching
LEFT = Keep left
RIGHT = Keep right
FULL = Keep all
CROSS = Multiply
SELF = Same table
Practice:
Study:
Memorize:
ACID:
All or nothing
Correct state
Independent execution
Data survives
2PL:
Growing → Lock point → Shrinking
Graph:
No cycle → Serializable
Cycle → Not serializable
Practice:
DDL:
CREATE, ALTER, DROP, TRUNCATE
DML:
INSERT, UPDATE, DELETE
DQL:
SELECT
DCL:
GRANT, REVOKE
TCL:
COMMIT, ROLLBACK, SAVEPOINT
WHERE:
Filters rows
HAVING:
Filters groups
BETWEEN:
Inclusive
LIKE:
% = Any number of characters
_ = Exactly one character
INNER:
Matches only
LEFT:
All left rows
RIGHT:
All right rows
FULL:
All rows
CROSS:
Left count × Right count
SELF:
Table joined to itself
Correlated:
Uses outer-query value
ACID:
Atomicity, Consistency, Isolation, Durability
S-lock:
Read
X-lock:
Write
2PL:
Growing then shrinking
Strict 2PL:
Hold X-locks until commit or abort
NoSQL:
Key-value, Document, Wide-column, Graph