Back to blog
Core CS

SQL — Complete Interview Notes

Comprehensive SQL guide covering DDL, DML, joins, subqueries, window functions, indexes, and query optimization for technical interviews.

Dhup Thumbadiya·July 26, 2026·12 min read

DDL

DDL commands define the structure of the database. CREATE builds it, ALTER modifies it, DROP deletes it entirely, TRUNCATE empties it but keeps the structure, and RENAME changes its name. Unlike DML commands, DDL commands are auto-commit, meaning they cannot be rolled back Here is your Ultra-Short DDL Query Guide – only queries and one important point per command. No theory.

1. CREATE

CREATE TABLE Students ( Roll_No INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Age INT );

Important: Defines table structure. NOT NULL means column cannot be empty.

2. ALTER (Add Column)

ALTER TABLE Students ADD Email VARCHAR(100);

Important: Adds a new column to existing table.

3. ALTER (Modify Column)

ALTER TABLE Students MODIFY Name VARCHAR(100);

Important: Changes column datatype/size.

4. ALTER (Drop Column)

ALTER TABLE Students DROP COLUMN Age;

Important: Permanently removes a column.

5. DROP

DROP TABLE Students;

Important: Deletes table + data + structure completely. Cannot undo.

6. TRUNCATE

TRUNCATE TABLE Students;

Important: Deletes all rows but keeps empty table structure. Cannot undo.

7. RENAME

RENAME TABLE Students TO Learners;

Important: Changes table name. Data stays intact.

8. ALTER (Rename Column - DB specific)

ALTER TABLE Students RENAME COLUMN Name TO Student_Name;

Important: Some DBs use CHANGE (MySQL) or RENAME COLUMN (PostgreSQL).

9. ALTER (Add Primary Key)

ALTER TABLE Students ADD PRIMARY KEY (Roll_No);

Important: Adds PK after table creation.

10. ALTER (Drop Primary Key)

ALTER TABLE Students DROP PRIMARY KEY;

Important: Removes PK constraint.

DCL

Data Control Language

1. GRANT (Give Permissions)

GRANT SELECT, INSERT ON Students TO User1;

Important: Gives User1 permission to read (SELECT) and add (INSERT) data into the Students table.

GRANT ALL PRIVILEGES ON Students TO User1;

Important: Gives User1 all permissions (SELECT, INSERT, UPDATE, DELETE, ALTER, etc.) on the Students table.

GRANT SELECT ON Students TO User1, User2, User3;

Important: You can grant permissions to multiple users at once.

GRANT SELECT ON Students TO PUBLIC;

Important: PUBLIC means every user in the database gets this permission.

GRANT SELECT ON Students TO User1 WITH GRANT OPTION;

Important: WITH GRANT OPTION allows User1 to further grant the SELECT permission to other users.

2. REVOKE (Take Back Permissions)

REVOKE INSERT ON Students FROM User1;

Important: Removes User1's permission to insert data into the Students table.

REVOKE ALL PRIVILEGES ON Students FROM User1;

Important: Removes all permissions that User1 had on the Students table.

REVOKE GRANT OPTION ON Students FROM User1;

Important: Removes only the GRANT OPTION power from User1. User1 keeps other permissions but cannot grant them to others.

TCL :

Here is your Ultra-Short TCL (Transaction Control Language) Guide – only queries and one important point per command.

The Setup (One Table)

CREATE TABLE Accounts ( Acc_ID INT PRIMARY KEY, Balance DECIMAL(10,2) ); INSERT INTO Accounts VALUES (1, 1000), (2, 500);

1. COMMIT (Make Changes Permanent)

UPDATE Accounts SET Balance = Balance - 200 WHERE Acc_ID = 1; UPDATE Accounts SET Balance = Balance + 200 WHERE Acc_ID = 2; COMMIT;

Important: Saves all changes permanently to the database. After COMMIT, you cannot rollback.

2. ROLLBACK (Undo All Changes)

UPDATE Accounts SET Balance = Balance - 200 WHERE Acc_ID = 1; UPDATE Accounts SET Balance = Balance + 200 WHERE Acc_ID = 2; ROLLBACK;

Important: Undoes all changes since the last COMMIT. Database returns to original state (Acc1 = 1000, Acc2 = 500).

3. SAVEPOINT (Partial Rollback)

SAVEPOINT sp1; UPDATE Accounts SET Balance = Balance - 200 WHERE Acc_ID = 1; SAVEPOINT sp2; UPDATE Accounts SET Balance = Balance + 200 WHERE Acc_ID = 2; ROLLBACK TO sp2; -- Undoes only the 2nd update COMMIT;

Important: ROLLBACK TO sp2 undoes changes after sp2 only. The first update (Acc1 = 800) is kept.

4. ROLLBACK TO SAVEPOINT (Detailed Example)

SAVEPOINT start; UPDATE Accounts SET Balance = 800 WHERE Acc_ID = 1; -- Step 1 SAVEPOINT step1; UPDATE Accounts SET Balance = 700 WHERE Acc_ID = 1; -- Step 2 SAVEPOINT step2; UPDATE Accounts SET Balance = 600 WHERE Acc_ID = 1; -- Step 3 ROLLBACK TO step1; -- Undoes Step 2 & Step 3. Balance is back to 800. COMMIT;

Important: ROLLBACK TO step1 keeps changes until step1 (Balance = 800) and discards everything after.

5. RELEASE SAVEPOINT (Delete a Savepoint)

SAVEPOINT sp1; UPDATE Accounts SET Balance = 800 WHERE Acc_ID = 1; RELEASE SAVEPOINT sp1;

Important: Deletes the savepoint sp1. You can no longer rollback to it.

6. Auto-Commit (Interview Trap)

-- In MySQL, auto-commit is ON by default. SET AUTOCOMMIT = OFF; -- Now every query waits for manual COMMIT. UPDATE Accounts SET Balance = 800 WHERE Acc_ID = 1; COMMIT; -- Now changes are permanent.

Important: In most databases, AUTOCOMMIT is ON by default. Every INSERT/UPDATE/DELETE is auto-committed unless you start a transaction explicitly.

The Only Trap Question

Interviewer: "What happens if you ROLLBACK after COMMIT?"

Answer: Nothing. ROLLBACK only works on changes made after the last COMMIT. Once committed, changes are permanent and cannot be undone.

Real Interview Scenario (Step-by-Step)

Question: "You are transferring ₹200 from Account 1 to Account 2. Write a TCL-safe transaction."

START TRANSACTION; -- Explicitly start UPDATE Accounts SET Balance = Balance - 200 WHERE Acc_ID = 1; UPDATE Accounts SET Balance = Balance + 200 WHERE Acc_ID = 2; -- If both updates succeed: COMMIT; -- If any update fails (e.g., Acc1 has insufficient balance): ROLLBACK;

Here is your Ultra-Short SQL Cheat Sheet covering all essential commands in a concise, interview-friendly format.

1. SELECT & FILTERING

CommandSyntaxExample
SELECTSELECT col1, col2 FROM table;SELECT Name, Salary FROM Employees;
**SELECT ***SELECT * FROM table;SELECT * FROM Employees;
SELECT DISTINCTSELECT DISTINCT col FROM table;SELECT DISTINCT Dept FROM Employees;
WHEREWHERE conditionWHERE Salary > 50000
AND/OR/NOTCombine conditionsWHERE Dept='IT' AND Salary>60000
ORDER BYORDER BY col ASC/DESCORDER BY Salary DESC
LIMIT/TOPLIMIT n or TOP nSELECT * FROM Employees LIMIT 5;

2. DML (Data Manipulation)

CommandSyntaxExample
INSERTINSERT INTO table (cols) VALUES (vals);INSERT INTO Employees (ID, Name) VALUES (1, 'Alice');
UPDATEUPDATE table SET col=val WHERE condition;UPDATE Employees SET Salary=70000 WHERE ID=1;
DELETEDELETE FROM table WHERE condition;DELETE FROM Employees WHERE ID=1;

3. NULL Handling

CommandSyntaxExample
IS NULLWHERE col IS NULLSELECT * FROM Employees WHERE Manager_ID IS NULL;
IS NOT NULLWHERE col IS NOT NULLSELECT * FROM Employees WHERE Manager_ID IS NOT NULL;

4. AGGREGATE FUNCTIONS

FunctionSyntaxExample
COUNTCOUNT(col)SELECT COUNT(*) FROM Employees;
SUMSUM(col)SELECT SUM(Salary) FROM Employees;
AVGAVG(col)SELECT AVG(Salary) FROM Employees;
MAXMAX(col)SELECT MAX(Salary) FROM Employees;
MINMIN(col)SELECT MIN(Salary) FROM Employees;

5. PATTERN MATCHING (LIKE)

PatternMeaningExample
'A%'Starts with 'A'WHERE Name LIKE 'A%'
'%a'Ends with 'a'WHERE Name LIKE '%a'
'%or%'Contains 'or'WHERE Name LIKE '%or%'
'_r%'2nd letter is 'r'WHERE Name LIKE '_r%'
'A__%'Starts with 'A', min 3 charsWHERE Name LIKE 'A__%'

6. IN & BETWEEN

CommandSyntaxExample
INWHERE col IN (val1, val2)WHERE Dept IN ('IT', 'HR')
BETWEENWHERE col BETWEEN val1 AND val2WHERE Salary BETWEEN 50000 AND 80000

7. JOINS

Join TypeSyntaxUse Case
INNER JOINSELECT * FROM t1 INNER JOIN t2 ON t1.id = t2.id;Matching rows only
LEFT JOINSELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id;All from left, matches from right
RIGHT JOINSELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id;All from right, matches from left
FULL JOINSELECT * FROM t1 FULL JOIN t2 ON t1.id = t2.id;All from both tables

8. GROUP BY & HAVING

CommandSyntaxExample
GROUP BYGROUP BY colSELECT Dept, COUNT(*) FROM Employees GROUP BY Dept;
HAVINGHAVING conditionSELECT Dept, COUNT(*) FROM Employees GROUP BY Dept HAVING COUNT(*) > 2;

Key Point: WHERE filters rows before grouping. HAVING filters groups after grouping.

9. UNION

CommandSyntaxExample
UNIONSELECT ... UNION SELECT ...Removes duplicates
UNION ALLSELECT ... UNION ALL SELECT ...Keeps duplicates

Rule: Both SELECT statements must have the same number of columns and similar data types.

10. DDL (Data Definition Language)

CommandSyntaxExample
CREATE DATABASECREATE DATABASE db_name;CREATE DATABASE Company;
DROP DATABASEDROP DATABASE db_name;DROP DATABASE Company;
CREATE TABLECREATE TABLE table (col datatype);CREATE TABLE Employees (ID INT, Name VARCHAR(50));
DROP TABLEDROP TABLE table;DROP TABLE Employees;
TRUNCATETRUNCATE TABLE table;Deletes all rows, keeps structure
ALTER ADDALTER TABLE table ADD col datatype;ALTER TABLE Employees ADD Email VARCHAR(100);
ALTER DROPALTER TABLE table DROP COLUMN col;ALTER TABLE Employees DROP COLUMN Email;
ALTER MODIFYALTER TABLE table MODIFY col datatype;ALTER TABLE Employees MODIFY Name VARCHAR(100);

11. DCL (Data Control Language)

CommandSyntaxExample
GRANTGRANT privilege ON table TO user;GRANT SELECT ON Employees TO User1;
REVOKEREVOKE privilege ON table FROM user;REVOKE SELECT ON Employees FROM User1;

12. TCL (Transaction Control Language)

CommandSyntaxExample
COMMITCOMMIT;Saves all changes permanently
ROLLBACKROLLBACK;Undoes all changes since last commit
SAVEPOINTSAVEPOINT sp_name;Creates a bookmark
ROLLBACK TOROLLBACK TO sp_name;Undoes changes after savepoint

13. CONSTRAINTS (Quick Reference)

ConstraintPurposeSyntax Example
PRIMARY KEYUnique + Not NullID INT PRIMARY KEY
FOREIGN KEYReferences another tableDept_ID INT REFERENCES Departments(ID)
UNIQUEAll values must be differentEmail VARCHAR(100) UNIQUE
NOT NULLCannot be emptyName VARCHAR(50) NOT NULL
CHECKCustom conditionAge INT CHECK (Age >= 18)
DEFAULTDefault value if none providedStatus VARCHAR(10) DEFAULT 'Active'

SUBQUERIES (Query inside a Query)

TypeDescriptionExample
Scalar SubqueryReturns single value (1 row, 1 col)SELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Row SubqueryReturns single row (multiple columns)SELECT * FROM Employees WHERE (Dept, Salary) = (SELECT Dept, MAX(Salary) FROM Employees GROUP BY Dept LIMIT 1);
Table SubqueryReturns table (multiple rows/cols)SELECT * FROM (SELECT Dept, AVG(Salary) AS Avg_Sal FROM Employees GROUP BY Dept) AS Dept_Avg WHERE Avg_Sal > 60000;
Correlated SubqueryReferences outer query (runs row by row)SELECT * FROM Employees e1 WHERE Salary > (SELECT AVG(Salary) FROM Employees e2 WHERE e2.Dept = e1.Dept);

Subquery with IN / EXISTS / ANY / ALL

KeywordDescriptionExample
INMatches any value in listSELECT * FROM Employees WHERE Dept_ID IN (SELECT Dept_ID FROM Departments WHERE Location = 'NYC');
NOT INDoes not match any valueSELECT * FROM Employees WHERE Dept_ID NOT IN (SELECT Dept_ID FROM Departments WHERE Location = 'LA');
EXISTSReturns TRUE if subquery has rowsSELECT * FROM Employees e WHERE EXISTS (SELECT 1 FROM Assignments a WHERE a.Emp_ID = e.Emp_ID);
NOT EXISTSReturns TRUE if subquery is emptySELECT * FROM Employees e WHERE NOT EXISTS (SELECT 1 FROM Assignments a WHERE a.Emp_ID = e.Emp_ID);
ANYCompares to any value in subquerySELECT * FROM Employees WHERE Salary > ANY (SELECT Salary FROM Employees WHERE Dept = 'HR');
ALLCompares to all values in subquerySELECT * FROM Employees WHERE Salary > ALL (SELECT Salary FROM Employees WHERE Dept = 'HR');

Subquery in SELECT / FROM / WHERE / HAVING

LocationExample
SELECTSELECT Name, (SELECT AVG(Salary) FROM Employees) AS Company_Avg FROM Employees;
FROMSELECT * FROM (SELECT Dept, AVG(Salary) AS Avg_Sal FROM Employees GROUP BY Dept) AS Sub;
WHERESELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);
HAVINGSELECT Dept, AVG(Salary) FROM Employees GROUP BY Dept HAVING AVG(Salary) > (SELECT AVG(Salary) FROM Employees);
GitHub
LinkedIn