
Top 100 SQL Interview Questions & Answers — Complete Guide
Table of Contents
ToggleCovers top 100 SQL interview questions, SQL query interview questions, SQL interview questions for analytics, and database testing interview questions for freshers. Use the search to jump to any topic.
Contents
SQL Interview Questions for Freshers – Basics (Q1–20)
Start your preparation with these Top SQL Interview Questions [2025]. This first part covers SQL basics, queries, WHERE clause, JOINS, GROUP BY, HAVING, subqueries and more. Perfect for freshers, analytics SQL interview questions, and SQL query interview practice.
1. What is SQL, and why is it important in Data Analytics?
Answer: SQL (Structured Query Language) is used to manage and query relational databases. It’s vital in data analytics for querying datasets, generating reports, and supporting business insights.
2. Difference between SELECT
and SELECT DISTINCT
?
Answer: SELECT
retrieves all rows including duplicates, while SELECT DISTINCT
removes duplicates and shows unique results.
SELECT DISTINCT department FROM employees;
3. How do you retrieve all columns from a table?
Answer: Use *
with SELECT.
SELECT * FROM employees;
4. What is the purpose of the WHERE clause?
Answer: It filters rows before the output is returned.
SELECT name FROM employees WHERE salary > 50000;
5. What are the main types of SQL JOINs?
Answer: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN.
SELECT e.name, d.department_name FROM employees e INNER JOIN departments d ON e.dept_id = d.dept_id;
6. What is a Primary Key?
Answer: A column that uniquely identifies each row and cannot be NULL.
7. What is a Foreign Key?
Answer: A column in one table that refers to the Primary Key of another table, maintaining referential integrity.
8. How do you sort query results?
Answer: Use ORDER BY clause.
SELECT name, salary FROM employees ORDER BY salary DESC;
9. What does GROUP BY do?
Answer: Groups rows with the same values for aggregate calculations.
10. What is the HAVING clause?
Answer: HAVING filters groups after aggregation, unlike WHERE which filters rows before grouping.
11. Difference between WHERE and HAVING?
Answer: WHERE → filters rows, HAVING → filters groups.
12. How do you limit the number of rows?
Answer: Use LIMIT (MySQL/Postgres) or TOP (SQL Server).
13. What are Aggregate Functions?
Answer: COUNT, SUM, AVG, MIN, MAX.
14. How do you handle NULL values?
Answer: Use IS NULL / IS NOT NULL, or functions like COALESCE.
15. What is the COALESCE function?
Answer: Returns the first non-NULL value in a list.
16. Difference between DELETE and TRUNCATE?
Answer: DELETE removes selected rows and is rollback-able; TRUNCATE removes all rows, faster, less reversible.
17. How do you update data in a table?
Answer: Use UPDATE with SET.
18. What is a Subquery?
Answer: A query inside another query to fetch intermediate results.
19. How do you count paying customers by city?
Answer: Use GROUP BY with a WHERE filter.
SELECT city, COUNT(*) FROM customers WHERE is_paying = 1 GROUP BY city;
20. What is the difference between correlated and non-correlated subqueries?
Answer: Non-correlated runs once independently; correlated depends on outer query and runs per row.
⭐ Continue with Part 2 (Q21–40) for Intermediate SQL Interview Questions.
Go to Part 2 →Intermediate SQL Interview Questions (Q21–40)
This part covers intermediate SQL interview questions including table creation, CASE statements, duplicates, UNION, ALTER, IN, BETWEEN, VIEWS, LIKE, indexes and more. These are often asked in SQL interview questions for analytics and database testing interview questions for freshers.
21. How do you create a table in SQL?
Answer: Use the CREATE TABLE
statement with columns and data types.
CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(100) );
22. What is the CASE statement used for?
Answer: Adds conditional logic to queries.
SELECT name, CASE WHEN salary > 50000 THEN 'High' ELSE 'Low' END AS salary_category FROM employees;
23. How do you find duplicate rows in a table?
Answer: Use GROUP BY with HAVING.
SELECT email, COUNT(*) as cnt FROM customers GROUP BY email HAVING COUNT(*) > 1;
24. What is the UNION operator?
Answer: Combines results of two queries and removes duplicates.
25. Difference between UNION and UNION ALL?
Answer: UNION removes duplicates, UNION ALL keeps all records (faster).
26. How to add a new column in a table?
Answer: Use ALTER TABLE ADD.
ALTER TABLE employees ADD hire_date DATE;
27. What is the IN operator?
Answer: Tests whether a value matches any value in a list.
28. What is the BETWEEN operator?
Answer: Selects values within a range, inclusive of boundaries.
29. How do you rename a table?
Answer: Use ALTER TABLE RENAME TO.
30. What is a View in SQL?
Answer: A virtual table based on a SELECT query. It simplifies access to complex queries.
31. How do you drop a table?
Answer: Use DROP TABLE to delete the table permanently.
32. What is the LIKE operator?
Answer: Used for pattern matching with wildcards (% and _).
33. How do you concatenate strings in SQL?
Answer: Use CONCAT() or || depending on the database.
34. What is the purpose of an Index in SQL?
Answer: Speeds up data retrieval at the cost of additional storage.
35. How to find the second highest salary?
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
36. What is Normalization?
Answer: Process of organizing data to minimize redundancy and improve integrity (1NF, 2NF, 3NF).
37. What is Denormalization?
Answer: Adding redundancy back to improve read performance (common in data warehouses).
38. How do you calculate total sales by month?
SELECT MONTH(order_date) as month, SUM(amount) as total_sales FROM orders GROUP BY MONTH(order_date);
39. What is a Self Join?
Answer: A join of a table with itself to compare rows.
40. How to handle case-sensitive string comparisons?
Answer: Convert both values with LOWER() or UPPER() before comparing.
⭐ Continue with Part 3 (Q41–60) for Advanced SQL Functions and Analytics Interview Questions.
Go to Part 3 →Advanced SQL Interview Questions (Q41–60)
These advanced SQL interview questions include COUNT behavior, pivoting, window functions, ranking, EXISTS, transactions, making them ideal for SQL interview questions for analytics and intermediate SQL interview practice.
41. How does the COUNT function handle NULLs?
Answer: COUNT(column)
ignores NULLs, while COUNT(*)
counts all rows.
42. How do you pivot data in SQL?
Answer: Transform rows into columns using CASE or PIVOT operators.
SELECT department, SUM(CASE WHEN year=2023 THEN sales ELSE 0 END) AS sales_2023, SUM(CASE WHEN year=2024 THEN sales ELSE 0 END) AS sales_2024 FROM sales_data GROUP BY department;
43. Difference between INNER JOIN and LEFT JOIN?
Answer: INNER JOIN → only matching rows; LEFT JOIN → all rows from left + matched rows from right.
44. How do you calculate a running total in SQL?
Answer: Use a window function with SUM() OVER
.
45. What is a Window Function?
Answer: Performs calculations across related rows without collapsing them. Examples: ROW_NUMBER()
, RANK()
, SUM() OVER
.
46. How do you remove duplicate rows?
Answer: Use ROW_NUMBER()
in a CTE to identify and delete duplicates.
47. What is the EXISTS operator?
Answer: Checks if a subquery returns rows; often used in correlated subqueries.
48. How do you find the Top 5 highest-paid employees?
Answer: Order results by salary and use LIMIT/TOP.
49. Difference between RANK and DENSE_RANK?
Answer: RANK skips numbers after ties; DENSE_RANK does not skip.
50. How do you calculate % contribution of each department?
SELECT department, SUM(sales) as dept_sales, (SUM(sales) / SUM(SUM(sales)) OVER())*100 as pct FROM sales_data GROUP BY department;
51. What is a Database?
Answer: An organized collection of data stored electronically, managed by a DBMS.
52. What is a Table?
Answer: A structure of rows and columns to store related data.
53. What is a Column in a database?
Answer: Vertical entity in a table representing an attribute (e.g., Name, Salary).
54. What is a Row in a database?
Answer: A single record in a table (horizontal entry).
55. What is a Query?
Answer: A request written in SQL to retrieve, insert, update, or delete data.
56. What is a DBMS?
Answer: Database Management System – software to manage, secure, and query databases.
57. What is a Relational Database?
Answer: Organizes data into tables connected by keys (Primary/Foreign).
58. What is a Primary Key?
Answer: A unique identifier for rows, cannot be NULL.
59. What is a Foreign Key?
Answer: A field that references the primary key of another table to enforce integrity.
60. What is Data Integrity?
Answer: Accuracy and consistency of data, enforced by constraints like PK, FK, UNIQUE.
⭐ Continue with Part 4 (Q61–80) for SQL Constraints, Joins, and Normalization Interview Questions.
Go to Part 4 →SQL Constraints, Joins & Optimization (Q61–80)
This section focuses on SQL constraints, joins, indexing, normalization, and transaction control. These are frequent in database testing interview questions for freshers and analytics SQL interview questions.
61. What are SQL Constraints?
Answer: Rules applied to columns to maintain data integrity (NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT).
62. Difference between UNIQUE and PRIMARY KEY?
Answer: PRIMARY KEY = unique + not null; UNIQUE = allows one NULL (except in Oracle).
63. What is a Composite Key?
Answer: A combination of two or more columns used to uniquely identify a row.
64. What is an Index in SQL?
Answer: A performance optimization tool that speeds up SELECT queries but adds overhead to INSERT/UPDATE.
65. What are the types of Indexes?
Answer: Clustered Index (sorts data physically) and Non-Clustered Index (logical reference to data).
66. What is a Transaction in SQL?
Answer: A single unit of work that executes a set of queries. Transactions follow ACID properties.
67. What are the ACID properties?
Answer: Atomicity, Consistency, Isolation, Durability.
68. Difference between COMMIT and ROLLBACK?
Answer: COMMIT saves all changes permanently; ROLLBACK undoes uncommitted changes.
69. What is SAVEPOINT in SQL?
Answer: Creates a point within a transaction to which you can ROLLBACK partially.
70. What is a Deadlock in SQL?
Answer: A situation where two transactions block each other by holding locks on resources required by the other.
71. What is a Self Join?
Answer: A table joined with itself to compare rows.
72. Difference between Cross Join and Inner Join?
Answer: CROSS JOIN → Cartesian product of two tables; INNER JOIN → matches rows based on condition.
73. What is Referential Integrity?
Answer: Ensures that foreign keys correctly reference primary keys in related tables.
74. Difference between DELETE, TRUNCATE and DROP?
- DELETE: removes selected rows, can ROLLBACK.
- TRUNCATE: removes all rows, cannot use WHERE.
- DROP: removes entire table.
75. What is Normalization in SQL?
Answer: A process of organizing data into multiple tables to reduce redundancy and improve integrity (1NF → 5NF).
76. What is Denormalization?
Answer: The process of adding redundancy for faster read performance (used in analytics databases).
77. How do you optimize SQL queries?
Answer: Use indexes, avoid SELECT *, use proper joins, and limit subqueries.
78. What is a Stored Procedure?
Answer: A saved block of SQL code that can be reused, often used for business logic in databases.
79. What is a Trigger?
Answer: An automatic action executed in response to events like INSERT, UPDATE, DELETE.
80. What is a Cursor in SQL?
Answer: A pointer that allows row-by-row processing of query results (used in procedural SQL).
⭐ Continue with Part 5 (Q81–100) for SQL Programming, Advanced Analytics & Final Prep.
Go to Part 5 →Advanced Analytics, CTEs & Real-World Scenarios (Q81–100)
Final set from the Top 100 SQL Interview Questions [2025]: CTEs (including recursive), window functions (LAG/LEAD), analytical patterns, JSON, date/time, star vs snowflake, OLTP vs OLAP, testing/QA. Perfect for analytics SQL interview questions and SQL query interview questions used in real data teams.
81. What is a CTE and why use it?
Answer: A Common Table Expression (WITH
) is a temporary, named result set used to simplify complex queries, improve readability, and support recursion.
WITH dept_avg AS ( SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id ) SELECT e.name, e.salary, d.avg_sal FROM employees e JOIN dept_avg d ON e.dept_id = d.dept_id;
82. What is a recursive CTE?
Answer: A CTE that references itself to traverse hierarchies (e.g., org charts, category trees).
WITH RECURSIVE chain AS ( SELECT emp_id, manager_id, 0 AS lvl FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.emp_id, e.manager_id, c.lvl+1 FROM employees e JOIN chain c ON e.manager_id = c.emp_id ) SELECT * FROM chain;
83. Difference between CTE and subquery?
Answer: Both produce derived result sets; CTEs are named and reusable within a statement, improve readability, and support recursion. Subqueries are inline and not reusable.
84. Use LAG/LEAD to compare rows
Answer: Window functions to access prior/next row values without self-joins.
SELECT order_id, order_date, amount, LAG(amount) OVER (ORDER BY order_date) AS prev_amt, LEAD(amount) OVER (ORDER BY order_date) AS next_amt FROM orders;
85. Nth highest salary pattern
Answer: Use DENSE_RANK()
over salary and filter by rank.
WITH r AS ( SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees ) SELECT name, salary FROM r WHERE rnk = 3; -- 3rd highest
86. Find customers with no orders (anti-join)
Answer: Use LEFT JOIN ... WHERE o.id IS NULL
or NOT EXISTS
.
SELECT c.customer_id, c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id WHERE o.customer_id IS NULL; -- OR SELECT c.customer_id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
87. Window frame clauses (RANGE/ROWS) use?
Answer: Define which rows participate in the window calculation (e.g., rolling 7 days vs all prior rows).
SELECT dt, amount, SUM(amount) OVER (ORDER BY dt ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rolling_7 FROM daily_sales;
88. Star vs Snowflake schema
Answer: Star: denormalized dimensions around a fact table (simpler, faster queries). Snowflake: normalized dimensions (less redundancy, more joins). Common in analytics SQL interview questions.
89. OLTP vs OLAP
Answer: OLTP: transactional, many small writes; OLAP: analytical, large reads across history. Different indexing and schema strategies.
90. Materialized view vs view
Answer: View is virtual; materialized view stores results physically for faster reads (needs refresh).
91. Query to get monthly active users (MAU)
Answer: Count distinct users per month from activity table.
SELECT DATE_TRUNC('month', activity_at) AS mth, COUNT(DISTINCT user_id) AS mau FROM user_activity GROUP BY 1 ORDER BY 1;
92. Cohort retention query pattern
Answer: Build cohorts by first activity month and measure active users in subsequent months.
WITH first_seen AS ( SELECT user_id, DATE_TRUNC('month', MIN(activity_at)) AS cohort FROM user_activity GROUP BY 1 ), activity AS ( SELECT user_id, DATE_TRUNC('month', activity_at) AS act_month FROM user_activity ) SELECT f.cohort, a.act_month, COUNT(DISTINCT a.user_id) AS retained FROM first_seen f JOIN activity a USING (user_id) GROUP BY 1,2 ORDER BY 1,2;
93. JSON handling in SQL (example)
Answer: Use JSON operators/functions to extract fields (DB-specific).
-- Postgres example SELECT payload->>'event' AS event_type, (payload->>'amount')::NUMERIC AS amount FROM events;
94. Date/time pitfalls to watch
Answer: Time zones, DST shifts, inclusive/exclusive ranges, and using DATE_TRUNC
for grouping. Always store UTC and display local time in apps.
95. Database testing checks for freshers
Answer: Validate counts, duplicates, referential integrity, NULL policy, and boundary values.
-- Count mismatch SELECT 'orders' AS tbl, COUNT(*) FROM orders UNION ALL SELECT 'order_items', COUNT(DISTINCT order_id) FROM order_items;
96. SQL queries for employee data — examples
Answer: Common interview mini-tasks.
-- Avg salary by department SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id; -- Employees hired last 30 days SELECT * FROM employees WHERE hire_date >= CURRENT_DATE - INTERVAL '30 day';
97. Transaction isolation levels
Answer: Read Uncommitted, Read Committed, Repeatable Read, Serializable — control phenomena like dirty/non-repeatable reads and phantom rows.
98. Why check the execution plan?
Answer: To understand how the optimizer executes a query (scans vs seeks, join strategies, index usage) and to fix bottlenecks.
99. UPSERT pattern (MERGE / ON CONFLICT)
Answer: Insert if not exists, else update — keeps data idempotent and consistent.
-- Postgres INSERT INTO customers (customer_id, name, email) VALUES (1, 'Asha', 'asha@x.com') ON CONFLICT (customer_id) DO UPDATE SET email = EXCLUDED.email;
100. End-to-end analytics case: top product by revenue per month
Answer: Combine aggregation + window ranking to pick the monthly winner (classic sql interview questions for analytics).
WITH monthly AS ( SELECT DATE_TRUNC('month', o.order_date) AS mth, oi.product_id, SUM(oi.qty * oi.price) AS revenue FROM orders o JOIN order_items oi ON o.order_id = oi.order_id GROUP BY 1,2 ), ranked AS ( SELECT *, RANK() OVER (PARTITION BY mth ORDER BY revenue DESC) AS rnk FROM monthly ) SELECT mth, product_id, revenue FROM ranked WHERE rnk = 1 ORDER BY mth;
Advanced Analytics, CTEs & Real-World Scenarios (Q81–100)
Final set from the Top 100 SQL Interview Questions [2025]: CTEs (including recursive), window functions (LAG/LEAD), analytical patterns, JSON, date/time, star vs snowflake, OLTP vs OLAP, testing/QA. Perfect for analytics SQL interview questions and SQL query interview questions used in real data teams.
🎉 You’ve completed the Top 100 SQL Interview Questions and Answers [2025]! Download the PDF or continue practicing with projects.
📥 Download Full PDF (Q1–100)Download: Top 100 SQL Interview Questions [2025] (PDF)
Perfect for last-minute revision. Includes SQL query interview questions, analytics SQL interview questions, and database testing checks for freshers.
Download PDF Join Free Sunday Demo ClassSQL Interview MCQ Quiz — 2025 (Part 1–5, 24 Qs)
employees
?WHERE
clause?GROUP BY
is used to…HAVING
:COALESCE(a,b,c)
return?hire_date DATE
column to employees:LIKE
to find emails ending with @x.com
?COUNT()
handle NULLs?🎉 Result
Tip: Use Toggle Review to reveal correct/incorrect highlights. You can also open the full answer key below.
📜 Show Answer Key (All 24)
🛈 Use this section in Elementor → HTML widget. Matches Vista Academy’s dark + gold theme.
📞 +91 94117 78145 | 📧 thevistaacademy@gmail.com | 💬 WhatsApp