Most data, backend, and analyst jobs will hinge on your ability to answer SQL interview questions. Although interviewers will test your knowledge of SQL, they also wish to assess your understanding of advanced techniques, including exclusion, join efficiency, and formatting in order to solve business-related problems. Below is a list of key SQL interview questions and answers that range in difficulty from basic to more in-depth. If you would like to develop your SQL querying abilities from scratch, then take a look at our in-depth SQL course syllabus, which allows you to fully grasp all topics through application.
SQL Interview Questions and Answers for Freshers
1. What is SQL, and why is it used?
SQL (Structured Query Language) is widely used as a programming language to store, manipulate, and control structured data within relational databases, including MySQL, PostgreSQL, and SQL Server.
2. What is the difference between a PRIMARY KEY and a UNIQUE key?
Both PRIMARY KEYs and UNIQUE keys ensure data is unique. However, PRIMARY KEYs cannot hold NULLs, and there can only be one PRIMARY KEY per table. UNIQUE keys can have one NULL value.
3. What is a FOREIGN KEY in SQL?
A FOREIGN KEY is a column within one table that relates to the PRIMARY KEY of another, to ensure referential integrity and avoid incorrect or ‘orphaned’ relationships.
4. What is the difference between DELETE, TRUNCATE, and DROP?
DELETE can DELETE selected records (via its WHERE functionality), and this can subsequently be reversed. TRUNCATE rapidly clears all table data but maintains the table definition. DROP will irrevocably DELETE a table.
5. What is the difference between WHERE and HAVING clauses?
While WHERE is used to select relevant rows before grouping, HAVING is applied to the groups formed by GROUP BY and can involve functions such as COUNT or SUM to further analyse data.
6. Explain the difference between INNER JOIN and LEFT JOIN.
INNER JOIN will only show those rows that have a corresponding key. LEFT JOIN, on the other hand, will show every row in the left table, with corresponding right table fields being set to NULL if there is no match.
7. What is the difference between UNION and UNION ALL?
Whilst both methods merge data from several SELECT queries (with equivalent columns), UNION will automatically disregard any duplicate data. UNION ALL will retain all data, even if this includes duplicates, and so is quicker.
8. What are aggregate functions in SQL? Name five.
Aggregate functions analyse groups of rows and output one overall result. The quintessential aggregate functions within SQL are COUNT(), SUM(), AVG(), MIN() and MAX().
9. What is a NULL value in SQL, and how do you check for it?
NULL signifies that no value exists – it should not be confused with 0 or an empty string. Comparison cannot be made with = and so IS NULL or IS NOT NULL must be used.
10. What is normalization, and why is it important?
Normalization divides a database into interlinked, more compact tables. It enables data to be effectively stored by removing redundancy and avoiding update anomalies. Furthermore, it ensures that data is both precise and uniform throughout the database.
Dive deep into our SQL course in Chennai for further learning.
SQL Interview Questions and Answers for Experienced Professionals
1. How do you find duplicate records while keeping one row per entity?
Partition on business keys and order by either a timestamp or primary key, and apply windowing functions (such as ROW_NUMBER()). Then, within a common table expression, select rows where the number is higher than 1.
SQL
WITH ranked AS (
SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) AS rn
FROM users
)
SELECT id FROM ranked WHERE rn > 1;
2. When does HAVING differ from a pre-aggregation WHERE filter in performance?
Predicates can be applied to a table using WHERE, which filters data and so reduces the data that is then hashed/ sorted and grouped. HAVING is applied post-grouping. Filtering data within WHERE ensures only relevant data is processed.
SQL
SELECT dept_id, SUM(salary) AS payroll
FROM employees
WHERE status = ‘active’
GROUP BY dept_id
HAVING SUM(salary) > 500000;
13. How do you calculate a running total without losing detail rows?
Window functions allow running values to be calculated based on an ordered data set and also retain all original rows. Setting a window frame is important for correct running calculations if there are duplicates or missing values within ordered columns.
SQL
SELECT order_date, amount,
SUM(amount) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM daily_sales;
14. Why can NOT IN (subquery) return zero rows unexpectedly?
If there is at least one NULL in the subquery, then rows that do not match will return unknown and therefore be excluded. To ensure that boolean operations behave as expected, either NOT EXISTS or NULL exclusions can be used.
SQL
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = ‘cancelled’
);
15. How do you retrieve the Nth highest salary per department?
Whilst DENSE_RANK() does not leave gaps in the ranking when there are duplicates (unlike RANK()), wrapping can be used to distinctly identify rows for a specific rank within a partition.
SQL
WITH dept_ranks AS (
SELECT emp_id, dept_id, salary,
DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM salaries
)
SELECT emp_id, dept_id, salary FROM dept_ranks WHERE rnk = 3;
16. How do composite index column order and selectivity impact queries?
Composite indexes are subject to the left-prefix property. Index range scans can be avoided if leading index columns are not referenced. Highly selective equality conditions should be specified first, followed by range and/or ORDER BY columns.
SQL
CREATE INDEX idx_orders_tenant_status_created
ON orders (tenant_id, status, created_at);
SELECT id FROM orders
WHERE tenant_id = 42 AND status = ‘paid’ AND created_at >= ‘2026-01-01’;
17. What causes deadlocks in transactions, and how do you mitigate them?
Deadlocks occur if two transactions both possess locks that are required by the other. Follow a standard access sequence for tables and rows. Limit transaction length and apply correct isolation levels.
SQL
BEGIN;
UPDATE accounts SET balance = balance – 100 WHERE account_id = 10;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 20;
COMMIT;
18. How do you detect gaps or missing sequences in ordered data?
Use a LAG() function to compare current and prior rows in order to detect gaps in a series. This avoids repeatedly performing a self-join on a table and allows you to analyse these gaps.
SQL
SELECT invoice_num AS prev_num,
LEAD(invoice_num) OVER (ORDER BY invoice_num) AS next_num
FROM invoices;
19. Why can functions on indexed columns hurt query performance?
Use of functions/expressions on indexed columns can prevent indexes from being used. A table or index scan will then occur unless there is a function-based index. Reformulate where possible so that the indexed column is on one side of the condition.
SQL
SELECT id, created_at
FROM events
WHERE created_at >= DATE ‘2026-11-01’
AND created_at < DATE ‘2026-11-02’;
20. How do you upsert records safely under concurrent writes?
Leverage atomic insert/update statements (ON CONFLICT or MERGE) along with a uniqueness constraint, which ensures that multiple simultaneous insert operations will update existing data rather than error over key duplication or requiring separate select and insert stages.
SQL
INSERT INTO product_metrics (product_id, views)
VALUES (88, 1)
ON CONFLICT (product_id)
DO UPDATE SET views = product_metrics.views + EXCLUDED.views;
Conclusion
Whilst knowing why a particular query is structured in a specific way can help you to learn SQL much more effectively, it is also key that you practise. Whether you are new to SQL and are learning about joins and groupings or a SQL expert looking to fine-tune your knowledge of indexing and windows, practising will help you to overcome any apprehension and become adept at solving problems.
Try answering previous questions and then experiment by adapting them to different data sets. Furthermore, try to produce well-structured queries and challenge yourself to do so within time constraints. Looking to further develop your SQL expertise? Enroll in our software training institute in Chennai.