SQL INTERVIEW QUICK GUIDE (JOINS + COMMANDS + TOP QUERIES)
1. What is SQL?
SQL is a language to store, retrieve, and manipulate data in relational databases.
2. SQL vs NoSQL
SQL: Structured, relational, table-based.
NoSQL: Document/JSON, scalable, flexible schemas.
3. Primary Key
Uniquely identifies each row; cannot be NULL.
4. Foreign Key
Links two tables; references primary key of another table.
5. WHERE vs HAVING
WHERE filters rows before grouping.
HAVING filters groups after GROUP BY.
6. SQL JOINS (Simple)
INNER JOIN:
Returns only matching rows from both tables.
Example:
SELECT [Link], d.dept_name FROM employees e
INNER JOIN departments d ON e.dept_id = d.dept_id;
LEFT JOIN:
Returns all rows from left table + matches from right.
Example:
SELECT [Link], d.dept_name FROM employees e
LEFT JOIN departments d ON e.dept_id = d.dept_id;
RIGHT JOIN:
Returns all rows from right table + matches from left.
FULL JOIN:
All rows from both tables (match + no match).
CROSS JOIN:
Cartesian product: every row paired with every row.
SELF JOIN:
Table joined with itself.
7. SQL Commands
DDL (Structure):
CREATE, ALTER, DROP, TRUNCATE
DML (Data):
INSERT, UPDATE, DELETE
DQL:
SELECT
DCL:
GRANT, REVOKE
TCL (Transactions):
COMMIT, ROLLBACK, SAVEPOINT
8. Aggregate Functions
COUNT, SUM, AVG, MAX, MIN
9. GROUP BY Example
SELECT dept_id, COUNT(*) FROM employees GROUP BY dept_id;
10. ORDER BY Example
SELECT * FROM employees ORDER BY salary DESC;
11. Subquery Example
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
12. CTE Example
WITH avg_sal AS (SELECT AVG(salary) a FROM employees)
SELECT name FROM employees, avg_sal WHERE salary > a;
13. Window Function Example
SELECT name, salary, RANK() OVER(ORDER BY salary DESC) rank FROM employees;
14. CASE WHEN Example
SELECT name, CASE WHEN salary > 50000 THEN 'High' ELSE 'Low' END FROM employees;
15. IN / EXISTS Example
SELECT name FROM employees WHERE city IN (SELECT city FROM students);
SELECT [Link] FROM employees e
WHERE EXISTS (SELECT 1 FROM students s WHERE [Link] = [Link]);
16. DELETE vs TRUNCATE vs DROP
DELETE: removes rows (can use WHERE).
TRUNCATE: removes all rows instantly, no WHERE.
DROP: removes table structure.
17. Index Example
CREATE INDEX idx_emp_name ON employees(name);
18. 2nd Highest Salary
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
19. FULL JOIN Logic
JOIN merges rows; SELECT decides which columns show.