1. What is the difference between SQL and MySQL?
Answer: SQL is a language used for managing databases, while MySQL is a relational database
management system that uses SQL.
2. Explain ACID properties in SQL.
Answer:
- Atomicity: Ensures complete transactions or none at all.
- Consistency: Maintains database integrity.
- Isolation: Transactions are independent.
- Durability: Completed transactions persist even after a system failure.
3. What is the difference between clustered and non-clustered indexes?
Answer: A clustered index sorts and stores data rows in the table based on the key, while a
non-clustered index creates a separate structure from the data row.
4. How do you find duplicate records in a table?
Answer:
```sql
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1;
```
5. What is a CTE (Common Table Expression)?
Answer: A CTE is a temporary result set defined using WITH clause, used for simplifying complex
joins and subqueries.
6. What are window functions?
Answer: Functions like ROW_NUMBER(), RANK(), and LAG() that perform calculations across a set
of table rows related to the current row.
7. How do you improve SQL query performance?
Answer:
- Use indexes
- Avoid SELECT *
- Use WHERE clauses to filter early
- Avoid unnecessary joins
- Use EXISTS instead of IN where appropriate
8. What is the difference between IN and EXISTS?
Answer: IN is faster for small lists. EXISTS is better for checking presence in correlated subqueries
with larger data sets.
9. What is normalization and denormalization?
Answer: Normalization reduces redundancy and ensures data integrity. Denormalization increases
redundancy for faster read performance.
10. What is the difference between RANK() and DENSE_RANK()?
Answer: RANK() leaves gaps in ranking when there are ties, while DENSE_RANK() does not.
11. What is a surrogate key?
Answer: A surrogate key is an artificial key (usually an auto-increment number) used instead of a
natural key.
12. How would you retrieve the second highest salary from a table?
Answer:
```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
```
13. What are transactions and how are they controlled?
Answer: A transaction is a logical unit of work. It is controlled using COMMIT, ROLLBACK, and
SAVEPOINT.
14. Explain the difference between DELETE, TRUNCATE, and DROP.
Answer:
- DELETE removes specific rows and can be rolled back.
- TRUNCATE removes all rows and cannot be rolled back.
- DROP deletes the table structure entirely.
15. What are the types of JOINs in SQL?
Answer:
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL OUTER JOIN
- CROSS JOIN
- SELF JOIN