SQL Questions and Answers
1. Q: What is SQL?
A: SQL (Structured Query Language) is a language used to communicate with and
manipulate relational databases.
2. Q: What are the different types of SQL commands?
A: DDL, DML, DQL, DCL, and TCL.
3. Q: What is a Primary Key?
A: A column or set of columns that uniquely identifies each row in a table.
4. Q: What is a Foreign Key?
A: A key used to link two tables; it's a field in one table that refers to the primary key in
another.
5. Q: What is the difference between WHERE and HAVING?
A: WHERE filters rows before aggregation, HAVING filters after aggregation.
6. Q: How do you select unique records from a table?
A: SELECT DISTINCT column_name FROM table_name;
7. Q: What does NULL mean in SQL?
A: A NULL value represents missing or unknown data.
8. Q: How do you sort results in SQL?
A: Using ORDER BY column_name [ASC|DESC]
9. Q: How do you filter rows in SQL?
A: Using WHERE clause. Example: WHERE age > 30
10. Q: What is the default sorting order in SQL?
A: Ascending (ASC).
11. Q: How do you count the number of rows in a table?
A: SELECT COUNT(*) FROM table_name;
12. Q: How do you find the number of employees in each department?
A: SELECT department, COUNT(*) FROM employees GROUP BY department;
13. Q: How do you get the second highest salary?
A: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM
employees);
14. Q: What is a JOIN? Name its types.
A: A JOIN combines rows from two or more tables. Types: INNER, LEFT, RIGHT, FULL
OUTER, CROSS, SELF JOIN.
15. Q: Write a query to fetch employee names and their department names.
A: SELECT e.name, d.department_name FROM employees e INNER JOIN departments d
ON e.dept_id = d.id;
16. Q: What is a subquery?
A: A query inside another query.
17. Q: What is the difference between IN and EXISTS?
A: IN evaluates all values and loads them into memory. EXISTS returns true if subquery
returns any row.
18. Q: What is the difference between UNION and UNION ALL?
A: UNION removes duplicates, UNION ALL keeps them.
19. Q: What does GROUP BY do?
A: It groups rows that have the same values into summary rows.
20. Q: What is a correlated subquery?
A: A subquery that uses values from the outer query.
21. Q: Write a query to find duplicate records in a table.
A: SELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING COUNT(*)
> 1;
22. Q: What is a window function?
A: A function that performs a calculation across a set of rows related to the current row.
23. Q: Difference between RANK() and DENSE_RANK()?
A: RANK() skips numbers for ties; DENSE_RANK() doesn’t.
24. Q: How to retrieve the nth highest salary?
A: SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1
OFFSET
n-1;
25. Q: What is normalization?
A: Organizing data to reduce redundancy.
26. Q: How do you delete duplicate rows?
A: DELETE FROM employees a USING employees b WHERE a.id > b.id AND a.email =
b.email;
27. Q: What is a CTE?
A: Common Table Expression; a temporary result set defined using WITH clause.
28. Q: What is a recursive CTE?
A: A CTE that references itself for hierarchical data.
29. Q: What is the difference between DELETE and TRUNCATE?
A: DELETE: row-by-row, rollbackable; TRUNCATE: all rows instantly, not rollbackable.
30. Q: What is indexing?
A: Improves query performance by allowing faster data retrieval.
31. Q: Find employees who joined in the last 3 months.
A: SELECT * FROM employees WHERE join_date >= CURRENT_DATE - INTERVAL '3
months';
32. Q: Get the top 3 products by sales.
A: SELECT product_id, SUM(sales) AS total_sales FROM orders GROUP BY product_id
ORDER BY total_sales DESC LIMIT 3;
33. Q: List customers who didn’t place any order.
A: SELECT * FROM customers WHERE customer_id NOT IN (SELECT DISTINCT
customer_id FROM orders);
34. Q: Get monthly revenue for 2024.
A: SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) FROM orders
WHERE EXTRACT(YEAR FROM order_date) = 2024 GROUP BY 1 ORDER BY 1;
35. Q: Calculate running total of sales.
A: SELECT order_id, order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS
running_total FROM orders;
36. Q: Find employees with same salary.
A: SELECT salary FROM employees GROUP BY salary HAVING COUNT(*) > 1;
37. Q: Show department with highest average salary.
A: SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY
department_id ORDER BY avg_salary DESC LIMIT 1;
38. Q: Get employees hired in each year.
A: SELECT EXTRACT(YEAR FROM hire_date) AS year, COUNT(*) FROM employees GROUP
BY year ORDER BY year;
39. Q: Compare sales this month vs last month.
A: SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS total,
LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)) AS prev_total
FROM orders GROUP BY 1;
40. Q: Fetch customers with 2 or more orders in the same day.
A: SELECT customer_id, order_date FROM orders GROUP BY customer_id, order_date
HAVING COUNT(*) >= 2;
41. Q: Can a table have multiple primary keys?
A: No. Only one primary key (can be composite).
42. Q: What is a composite key?
A: A primary key made up of two or more columns.
43. Q: Can NULL be a part of a primary key?
A: No. Primary keys must be unique and not null.
44. Q: What’s the difference between CHAR and VARCHAR?
A: CHAR is fixed-length, VARCHAR is variable-length.
45. Q: How do you handle NULLs in aggregate functions?
A: Most aggregate functions ignore NULLs except COUNT(*).
46. Q: What is the purpose of CASE statement?
A: Conditional logic within SQL queries.
47. Q: How do you pivot data in SQL?
A: Using CASE with GROUP BY, or PIVOT clause (in some DBs).
48. Q: Can you use GROUP BY with window functions?
A: Yes, but window functions work on the full result set.
49. Q: What is the difference between a table and a view?
A: A table stores data; a view is a saved query result.
50. Q: What is denormalization?
A: Introducing redundancy into a table for faster reads.
51. Q: What is the difference between clustered and non-clustered index?
A: Clustered index sorts and stores data physically; non-clustered stores pointers.
52. Q: What is ACID in databases?
A: Atomicity, Consistency, Isolation, Durability.
53. Q: What is the difference between OLTP and OLAP?
A: OLTP: transactional; OLAP: analytical.
54. Q: What is normalization and why is it important?
A: To reduce redundancy and ensure data integrity.
55. Q: What is the purpose of 1NF, 2NF, and 3NF?
A: 1NF: no repeating groups; 2NF: no partial dependencies; 3NF: no transitive
dependencies.
56. Q: What is a surrogate key?
A: An artificial key used as the primary key.
57. Q: What is a natural key?
A: A key formed from real data attributes.
58. Q: What is referential integrity?
A: Ensures foreign keys match primary keys.
59. Q: What is a constraint in SQL?
A: Rules like NOT NULL, UNIQUE, CHECK, PRIMARY KEY.
60. Q: What is a schema in SQL?
A: A logical container for database objects.
61. Q: What is a materialized view?
A: A view that stores the result set physically.
62. Q: What are the disadvantages of indexing?
A: Slows down writes and uses disk space.
63. Q: What is the difference between DELETE, DROP, and TRUNCATE?
A: DELETE: removes rows; TRUNCATE: quick delete; DROP: removes table.
64. Q: What is data integrity?
A: Accuracy and consistency of data.
65. Q: What is an anomaly in SQL?
A: Issues like insert, delete, or update anomalies.
66. Q: What is a composite primary key?
A: Primary key made of multiple columns.
67. Q: What is an alias in SQL?
A: A temporary name using AS.
68. Q: Can a table have multiple foreign keys?
A: Yes.
69. Q: What is the default value of NULL + 100?
A: NULL.
70. Q: Can you use ORDER BY in a view?
A: Yes, but ordering isn’t guaranteed unless used in outer query.
71. Q: When should you use INDEX?
A: When columns are frequently filtered or sorted.
72. Q: When should you avoid using indexes?
A: On low-cardinality columns or write-heavy tables.
73. Q: What is a covering index?
A: Includes all columns needed by a query.
74. Q: What is the difference between TEMPORARY TABLE and CTE?
A: Temp table: physical; CTE: logical and temporary.
75. Q: What are scalar vs aggregate functions?
A: Scalar: per row (e.g., UPPER); Aggregate: per group (e.g., SUM).
76. Q: What is the use of COALESCE()?
A: Returns the first non-NULL value.
77. Q: How do NULLs affect DISTINCT?
A: NULLs are treated as duplicates.
78. Q: What is a transaction?
A: A group of operations executed as a unit.
79. Q: What is a deadlock?
A: Two transactions waiting for each other to release locks.
80. Q: What is the purpose of ISOLATION LEVEL in SQL?
A: Controls visibility of changes across transactions.