Common Interview Questions & Answers
18. Common Interview Questions & Answers
Section titled “18. Common Interview Questions & Answers”Q1: What is the difference between DELETE, TRUNCATE, and DROP?
Section titled “Q1: What is the difference between DELETE, TRUNCATE, and DROP?”| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Type | DML | DDL | DDL |
| WHERE clause | ✅ Yes | ❌ No | ❌ No |
| Rollback | ✅ Yes | ❌ No (mostly) | ❌ No |
| Triggers | ✅ Fires | ❌ No | ❌ No |
| AUTO_INCREMENT reset | ❌ No | ✅ Yes | N/A |
| Removes structure | ❌ No | ❌ No | ✅ Yes |
| Speed | Slow (row by row) | Fast | Instant |
Q2: Find the second highest salary.
Section titled “Q2: Find the second highest salary.”-- Method 1: LIMIT + OFFSETSELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
-- Method 2: SubquerySELECT MAX(salary) FROM employeesWHERE salary < (SELECT MAX(salary) FROM employees);
-- Method 3: DENSE_RANK (handles ties, nth salary)SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dr FROM employees) t WHERE dr = 2;Q3: Find duplicate records in a table.
Section titled “Q3: Find duplicate records in a table.”-- Find duplicate emailsSELECT email, COUNT(*) AS cntFROM employeesGROUP BY emailHAVING cnt > 1;
-- Get full rows of duplicatesSELECT * FROM employeesWHERE email IN ( SELECT email FROM employees GROUP BY email HAVING COUNT(*) > 1)ORDER BY email;
-- Delete duplicates (keep the lowest id)DELETE FROM employeesWHERE id NOT IN ( SELECT MIN(id) FROM employees GROUP BY email);Q4: What is the difference between UNION and UNION ALL?
Section titled “Q4: What is the difference between UNION and UNION ALL?”-- UNION removes duplicates (slower — sorts result)SELECT name FROM employeesUNIONSELECT name FROM contractors;
-- UNION ALL keeps duplicates (faster)SELECT name FROM employeesUNION ALLSELECT name FROM contractors;
-- Rules: same number of columns, compatible data typesQ5: What are the different types of indexes in MySQL?
Section titled “Q5: What are the different types of indexes in MySQL?”B-Tree Index → default, for =, <, >, BETWEEN, LIKE 'abc%'Hash Index → exact lookups only (MEMORY engine)Full-Text Index → text search with MATCH...AGAINSTSpatial Index → geospatial data (GIS)Covering Index → includes all query columnsComposite Index → multi-column B-Tree indexQ6: Explain GROUP BY with HAVING vs WHERE.
Section titled “Q6: Explain GROUP BY with HAVING vs WHERE.”-- WHERE filters rows BEFORE grouping-- HAVING filters AFTER grouping
SELECT dept_id, AVG(salary) AS avg_salFROM employeesWHERE hire_date > '2020-01-01' -- ← WHERE: filter rows firstGROUP BY dept_idHAVING avg_sal > 70000; -- ← HAVING: filter groups afterQ7: What is a self-join? Give an example.
Section titled “Q7: What is a self-join? Give an example.”-- Find all employees and their direct managersSELECT e.name AS employee, m.name AS managerFROM employees eLEFT JOIN employees m ON e.manager_id = m.id;-- LEFT JOIN ensures employees without managers (CEO) are includedQ8: Difference between CHAR and VARCHAR?
Section titled “Q8: Difference between CHAR and VARCHAR?”CHAR(10) → always stores 10 bytes (padded with spaces) → faster for fixed-length data → e.g., country_code CHAR(2), uuid CHAR(36)
VARCHAR(10) → stores only actual length + 1-2 length bytes → better for variable-length data → e.g., name VARCHAR(100), email VARCHAR(255)Q9: What is a covering index?
Section titled “Q9: What is a covering index?”A covering index is one that contains all the columns needed by a query — MySQL can answer the query purely from the index without reading the actual table rows. Look for Using index in EXPLAIN.
CREATE INDEX idx_covering ON employees(dept_id, salary, name);SELECT name, salary FROM employees WHERE dept_id = 1;-- EXPLAIN shows: Using index ← no table access neededQ10: What happens when you execute a SELECT query in MySQL?
Section titled “Q10: What happens when you execute a SELECT query in MySQL?”1. Client sends SQL to MySQL server2. Parser checks syntax, creates parse tree3. Preprocessor checks semantics (tables exist, permissions)4. Query Optimizer generates execution plan (cost-based)5. Execution Engine executes the plan6. Storage Engine (InnoDB) reads/fetches data7. Result sent back to clientQ11: Difference between correlated and non-correlated subquery?
Section titled “Q11: Difference between correlated and non-correlated subquery?”-- Non-correlated: inner query runs ONCESELECT name FROM employeesWHERE salary > (SELECT AVG(salary) FROM employees);
-- Correlated: inner query runs ONCE PER ROW of outer querySELECT name FROM employees e1WHERE salary > ( SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e1.dept_id -- ← references outer);-- Can be slow — consider rewriting with JOIN or CTEQ12: How do you optimize a slow query?
Section titled “Q12: How do you optimize a slow query?”Step-by-step approach:1. Run EXPLAIN / EXPLAIN ANALYZE to inspect execution plan2. Check type column — avoid ALL (full table scan)3. Add/fix indexes on WHERE, JOIN, ORDER BY columns4. Avoid functions on indexed columns in WHERE5. Rewrite subqueries as JOINs where possible6. Use LIMIT to reduce result set7. Check for N+1 query problems8. Review schema design (data types, normalization)9. Check slow query log for patterns10. Consider caching for repeated read-heavy queriesQ13: What is the difference between NOW() and CURRENT_TIMESTAMP?
Section titled “Q13: What is the difference between NOW() and CURRENT_TIMESTAMP?”NOW() -- returns datetime at start of statementCURRENT_TIMESTAMP -- synonym for NOW()SYSDATE() -- returns datetime at moment of execution -- (matters inside long stored procedures)
SELECT NOW(), SYSDATE();-- In most cases they return the same value-- Difference shows inside long-running SP or triggerQ14: How to get employees not in any department?
Section titled “Q14: How to get employees not in any department?”-- Method 1: LEFT JOIN + IS NULLSELECT e.*FROM employees eLEFT JOIN departments d ON e.dept_id = d.dept_idWHERE d.dept_id IS NULL;
-- Method 2: NOT IN (careful with NULLs!)SELECT * FROM employeesWHERE dept_id NOT IN (SELECT dept_id FROM departments);-- ⚠️ If any dept_id in departments is NULL, this returns no rows!
-- Method 3: NOT EXISTS (safe with NULLs)SELECT * FROM employees eWHERE NOT EXISTS ( SELECT 1 FROM departments d WHERE d.dept_id = e.dept_id);Q15: What is a deadlock and how does MySQL handle it?
Section titled “Q15: What is a deadlock and how does MySQL handle it?”A deadlock occurs when two transactions each hold a lock the other needs, causing infinite waiting. MySQL’s InnoDB automatically detects deadlocks and rolls back the transaction that has done the least work (innodb_deadlock_detect = ON by default).
-- Check deadlock infoSHOW ENGINE INNODB STATUS;-- Look for: LATEST DETECTED DEADLOCK sectionPrevention:
- Lock resources in consistent order
- Keep transactions short
- Use appropriate isolation level
- Avoid user interaction inside transactions