If you are unprepared for your SQL interview, walking into the interview room will become a nightmare, especially when the interviewer asks you to write a complex query on the spot. This is why memorizing only definitions is not enough. This is because, by asking Advanced SQL interview questions, interviewers eagerly want to analyze your problem-solving skills when a SQL query doesn’t work, data is duplicated, or a financial report badly needs a more complex calculation.
This guide covers the 40 must-know SQL questions for interview which our specialist team has organized these questions from basic concepts to advanced ones which are really suitable for freshers as well as experts.
Key Takeaways
- Basic SQL interview questions only test a candidate’s fundamental knowledge about keys, constraints, command types, and basic clauses.
- SQL interview questions on joins and aggregations are likely to appear in nearly every SQL technical interview.
- The advanced SQL query interview questions require writing real queries rather than defining basic concepts.
- Advanced SQL questions for interview cover CTEs, Windows functions, transactions, and query optimization.
Basic SQL Interview Questions
The following 10 basic SQL interview questions test whether candidates really understand the basic concepts of relational databases. Therefore, candidates must answer in simple, accurate terms and mention a real-time example when needed.
1. What is SQL?
SQL is an abbreviation of Structured Query Language, which is the standard programming language for managing and querying relational databases. It can retrieve records, insert raw data, update existing rows, delete information, create database objects, and control access.
2. What Are the Different Types of SQL Commands?
There are five different types of SQL commands, which are:
- DDL (Data Definition Language): CREATE, DROP, TRUNCATE, ALTER
- DQL (Data Query Language): SELECT
- DML (Data Manipulation Language): INSERT, UPDATE, DELETE
- DCL (Data Control Language): GRANT, REVOKE
- TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT
3. What is the Difference Between SQL and MySQL?
SQL is basically a query language that is used to work with relational database management systems (RDBMS). On the other hand, a server is actually an RDBMS that utilizes SQL. In simple terms, SQL is the query language, while MySQL is a database management system that efficiently understands and executes that query language. Moreover, other systems like PostgreSQL database, SQL Server, and Oracle server also use SQL with their individual extensions and syntax variations.
4. What is a Primary Key?
A Primary Key skillfully identifies each table record and strictly prohibits NULL values. Each table has normally only one primary key, although that primary key may contain multiple columns.
Moreover, this is one of the most frequently asked SQL interview questions for freshers, so you must practice it before sitting for an interview.
5. What is a Foreign Key?
A Foreign Key identifies and creates a relationship between tables by referencing a primary key in another table. This maintains “referential integrity,” guaranteeing that you cannot have “orphan” items that point to non-existent data in a parent table.
6. What is the Difference Between Primary Key and Unique Key?
Both keys enforce uniqueness. However, the key difference is that a primary key doesn’t allow NULL values and is permitted only once per table. On the other hand, a unique key allows one NULL value in most of the different databases and a table can have several.
7. What Are Constraints in SQL?
Constraints are capable of limiting the data that a table can store. Common SQL constraints include NOT NULL, UNIQUE, FOREIGN KEY, PRIMARY KEY, DEFAULT, CHECK, and INDEX. Moreover, they enforce data integrity at the database level.
8. What is NULL in SQL?
In SQL, NULL refers to a value that is missing, not provided, or unknown in the database. It is not exactly the same as zero or an empty string. You can use the IS NULL or IS NOT NULL command to test it.
9. What is the Difference Between DELETE, DROP, and TRUNCATE?
- DELETE: It eliminates specific rows using a WHERE clause and can be rolled back.
- TURNCATE: It removes all the rows from a table.
- DROP: It removes the table itself along with its data
10. What is the Difference Between WHERE and HAVING?
WHERE filters row by row before grouping. HAVING filters grouped results following GROUP BY. For example, WHERE can filter employees by department, whereas HAVING can filter departments with average salaries greater than a certain amount.
After discussing SQL interview questions for freshers, let’s now understand questions for SQL interview candidates who are on intermediate-level stage.
Also Read: Computer Programming Jobs: 30 Ultimate Interview Questions And Answers
Intermediate SQL Interview Questions

These SQL interview questions and answers are related to relationships, aggregation, filtering and data management. In most cases, the interviewer will want to hear not only what a feature does at this point, but also when to apply it.
11. What Are JOINs in SQL?
JOINs combine the rows from more than two tables based on related columns. Here are the types of JOINs:
INNER JOIN
It retrieves records with matching values from both tables involved in the join. This is the most commonly used join for queries.
For example:
SELECT a.name, b.class FROM students a
INNER JOIN sections b ON a.dept_id = b.id;
LEFT (OUTER) JOIN
It retrieves all records/rows from the left table and the corresponding records/rows from the right table.
For example:
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
RIGHT JOIN
It retrieves all records/rows from the right table, as well as the matching records/rows from the left.
For example:
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
FULL JOIN
It returns matching and nonmatching rows from both sides where supported.
For example:
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
You can also learn more about INNER JOIN and OUTER JOIN in our Inner Join vs Outer Join: Understanding SQL Joins With Examples blog.
12. What is the Difference Between INNER JOIN and LEFT JOIN?
INNER JOIN only returns the rows in both tables that match. On the other hand, LEFT JOIN returns all rows from the left table, irrespective of whether a match takes place, and fills any mismatched right-side columns with NULL.
13. What is a SELF JOIN?
A Self JOIN is a type of regular JOIN in which a table connects to itself according to a relationship between its own column(s). A self-join employs the INNER JOIN or LEFT JOIN clauses, with a table alias used to assign distinct names to the tables within the query.
However, this is also one of the most frequently asked SQL interview questions.
14. What is a Subquery?
A subquery is an internal query nested within an external query. It is possible to nest it within SELECT, INSERT, UPDATE, or DELETE commands. When a subquery is present, it will be performed before the external statement.
15. What is the Difference Between a Subquery and a JOIN?
JOIN combines rows from tables together, and a subquery creates a temporary result set that is used in another query. Neither option is inherently quicker. The performance is dictated by the database query optimizer, indexing, data volume, and query architecture.
16. What is GROUP BY in SQL?
GROUP BY groups rows with the same value, so aggregate methods apply to each group. For example:
SELECT dept_id, COUNT(*) FROM students GROUP BY dept_id;
17. What Are Aggregate Functions in SQL?
An aggregate function operates on a collection of values to produce a single scalar value. The SELECT statement’s GROUP BY and HAVING clauses frequently employ aggregate functions. The following are the often-used SQL aggregate functions:
- AVG(): Calculates the mean of a set of numbers.
- COUNT(): Returns the total number of records in a specified table or view.
- MIN(): Finds the minimum of a set of values.
- MAX(): Finds the highest value in a collection of values.
- SUM(): Returns the sum of a collection of values.
- FIRST(): Returns the first element in a collection of values.
- LAST(): Returns the last entry in a collection of values.
Remember that all the above-mentioned aggregate functions ignore NULL value except for the COUNT function. You must prepare such types of SQL interview questions to qualify for the interview.
18. What is the Difference Between UNION and UNION ALL?
UNION joins two result sets and eliminates duplicates; thus, it’s essentially UNION ALL + DISTINCT. On the other hand, UNION ALL retains all rows, even duplicates, and is significantly quicker since it avoids the deduplication phase. Use UNION ALL when you are certain there are no duplicates or wish to keep them.
19. What is an Index in SQL?
An index in SQL refers to a database structure that can assist in locating the rows in a table quickly. An index is uniquely useful for most often filtered, sorted, or joined columns. However, excessive indexing has the risk of increasing storage and slowing down the INSERT, UPDATE, and DELETE functions.
20. What is Database Normalization?
Database normalization is the procedure of organizing a relational database to eliminate duplication and increase integrity. Common variants include 1NF (atomic values), 2NF (no incomplete dependencies), and 3NF (no transitive dependencies). Denormalization reverses this in terms of read performance.
After preparing these SQL questions for interview candidates, you will be able to secure a job as a junior SQL developer. So, if you have some experience working with SQL queries, you must prepare the following SQL interview questions for experienced candidates. These questions will help you secure higher positions or will help you get a promotion.
Also Read: SQL vs MySQL: Making The Right Database Choice For You
Advanced SQL Interview Questions

Advanced SQL interview questions evaluate candidates’ capacity to deal with advanced SQL features and reason about efficiency, rather than simply recalling definitions.
21. What is a Common Table Expression (CTE)?
A CTE or Common Table Expression refers to a temporary named result set that you may use in a SELECT, INSERT, UPDATE, or DELETE database query. CTEs increase query readability and let you split large queries into simpler, reusable components. The syntax includes the WITH keyword:
WITH reading_summary AS (
SELECT member_id, COUNT(*) AS books_read
FROM reading_log
GROUP BY member_id
)
SELECT m.member_name, r.books_read
FROM library_members m
JOIN reading_summary r ON m.id = r.member_id
WHERE r.books_read > 15;
22. What Are Window Functions in SQL?
Window functions conduct a computation over a collection of rows linked to the current row, but unlike aggregate functions, they do not combine the rows into a single result. Common Window function examples are ROW_NUMBER(), RANK(), SUM() OVER(), and LAG().
23. What is the Difference Between ROW_NUMBER(), RANK(), and DENSE_RANK()?
- ROW_NUMBER() generates a strictly unique, sequential integer for each row.
- RANK() assigns the same number to linked values while skipping the next numbers in sequence (e.g., 1, 2, 2, 4).
- DENSE_RANK() allocates the same number to ties but does not skip any numbers (e.g., 1, 2, 2, 3), so the ranking remains “dense.”
| Books Borrowed | ROW_NUMBER() | RANK() | DENSE_RANK() | What Happens |
|---|---|---|---|---|
| 20 | 1 | 1 | 1 | Highest borrowing count gets rank 1 |
| 20 | 2 | 1 | 1 | Same count shares the rank |
| 15 | 3 | 3 | 2 | RANK() skips 2, while DENSE_RANK() does not |
| 10 | 4 | 4 | 3 | Next distinct value gets the next rank |
You can present this table to the interviewer because this question is likely to be asked in SQL interview questions. So, you must prepare for these types of questions well.
24. What is a Stored Procedure?
A stored procedure is a subroutine that is accessible to programs that use a relational database management system (RDBMS). The database data dictionary stores such methods.
This question is likely to appear in stored procedure interview questions, so prepare well.
25. What is the Difference Between a Stored Procedure and a Function?
A function must return a value and can be used with a SELECT. A stored procedure can return zero or more values, conduct DML actions, and is invoked using EXECUTE.
26. What is a View in SQL?
A view is a saved query that functions as a virtual table. It can simplify difficult searches, limit access to specific columns or rows, and give a uniform interface to the underlying data.
27. What is a Database Transaction?
A transaction is a set of database actions handled as a single logical unit. It can be committed when successful or rolled back if a failure needs the changes to be reversed.
28. What Are ACID Properties?
ACID is an abbreviation for Atomicity, Consistency, Isolation, and Durability. They refer to the database transaction properties, which are further used for ensuring data validity in terms of errors and system failures.
- Atomicity: This property assures that the transaction is all-or-nothing.
- Consistency: This property guarantees that database modifications are legitimate and respect the rules and constraints.
- Isolation: This property guarantees the integrity of transactions that are visible to all other transactions.
- Durability: This property guarantees that committed transactions are permanently maintained in the database.
29. What is a Trigger in SQL?
A trigger is a category of stored procedure that automatically “fires” or operates in response to a definite event, such as an INSERT, UPDATE, or DELETE in a database. They are frequently used to audit modifications or enforce complicated business rules that basic constraints cannot accommodate.
30. How Can You Optimize a Slow SQL Query?
To improve a slow SQL query, decrease the amount of data examined, employ efficient indexing, and eliminate performance-draining syntax patterns.
Begin by evaluating the execution plan to identify the real bottleneck. Then:
- Create indexes for columns used in WHERE, JOIN, and ORDER BY clauses
- Instead of using SELECT *, choose only the columns you require.
- Filter early to decrease the rows processed downstream.
- Replace associated subqueries via JOINs wherever possible.
- Avoid functions on indexed columns in WHERE clauses, as they prohibit index utilization.
Practicing such SQL technical interview questions will surely help you pass your interview. Let’s now examine some of the SQL interview questions for queries.
Also Read: Cloud SQL Proxy: A Beginner’s Guide To Secure Database Connections
SQL Query Interview Questions

The SQL query interview questions and answers below are based on genuine problems that you may be asked to address during a technical interview. Instead of just reading the solutions, try entering these questions yourself.
31. How Do You Find Duplicate Records in a Table?
You can use a GROUP BY with HAVING query to detect duplicate records. For example:
SELECT phone numbers, COUNT(*) AS total FROM employees
GROUP BY numbers, HAVING COUNT(*) > 1;
32. How Do You Find the Second-Highest Salary?
You can use a subquery which is a common solution to find the second-highest salary among employees. For example:
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
33. How Do You Find the Nth-Highest Salary?
Use a Window function to find the nth highest salary among employees. For example:
SELECT salary
FROM (
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
) ranked
WHERE rank = 3; /*Change 3 to the desired rank*/
34. How Do You Remove Duplicate Rows in SQL?
You can use the following query to remove duplicate rows in SQL:
DELETE FROM users WHERE id NOT IN (
SELECT MIN(id) FROM users GROUP BY email
);
35. How Do You Find Employees Earning More Than the Average Salary?
Use the following query to find employees earning more than the average salary in an organization:
SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
36. How Do You Find the Top 3 Salaries in Each Department?
You can use the DENSE_RANK() function here to find the top 3 salaries in each department. For example:
SELECT * FROM (
SELECT name, dept_id, salary,
DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees
) t WHERE rnk <= 3;
37. How Do You Calculate a Running Total in SQL?
A window function can calculate a cumulative total:
SELECT order_date,
amount,
SUM(amount) OVER (
ORDER BY order_date
) AS running_total
FROM orders;
38. How Do You Find Records Present in One Table but Not Another?
To locate entries that exist in one table but not in another, you can use normal SQL techniques such as LEFT JOIN, NOT IN, NOT EXISTS, or set operators like EXCEPT / MINUS. Here is an example using LEFT JOIN:
SELECT a.* FROM table_a a
LEFT JOIN table_b b ON a.id = b.id
WHERE b.id IS NULL;
Let’s now discuss scenario-based SQL interview questions.
SQL Scenario-Based Interview Questions
Scenario questions evaluate your ability to reason through a database problem rather than just memorizing syntax. These SQL technical interview questions are very valuable for experienced applicants.
39. How Would You Improve a Query That Becomes Slow as a Table Grows?
Begin by running the execution plan to observe where your time is actually going. Check to see if the query is performing a complete table scan rather than utilizing an index.
Then work through:
- Filtering: Does the WHERE clause restrict rows prematurely?
- Indexes: Are the right columns indexed for this query pattern?
- JOINs: Are join columns indexed and properly typed?
- Data volume: Would dividing or preserving outdated data be beneficial?
- Columns: Is the query selecting more than necessary?
- Structure: Can subqueries be recast as JOINs or CTEs?
40. How Would You Design a Query to Return the Latest Record for Each Customer?
I will use a window function to rank records within each customer. Here is the query that I’ll be using:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY created_at DESC
) AS rn
FROM orders
) t WHERE rn = 1;
How To Prepare For an SQL Interview?
The best strategy to prepare for SQL interview questions for new and seasoned employees is to blend theory with hands-on experience. Instead of reading about questions, focus your preparation on creating them. For example:
- Practice writing queries manually without autocomplete.
- Master JOINs and aggregations first, since they feature in almost every interview.
- Get familiar with CTEs and window functions for advanced SQL interview questions.
- Understand indexes and how to read an execution plan.
- Explain your reasoning loudly while solving difficulties.
- Practice with datasets that include duplicates, NULLs, and edge situations.
If you are also looking for QA positions, practice the SQL interview questions for QA especially data validation, duplication detection, JOINs, filtering and finding out if database results match expected application behavior.
FAQs (Frequently Asked Questions)
What Are Basic SQL Interview Questions?
The basic interview questions for SQL normally cover the SQL basics like commands, keys, constraints, NULL, JOINs, aggregate, and filtering functions. Such questions mostly appear in almost every SQL interview questions for freshers.
What Are The 5 Basic SQL Commands?
The 5 basic SQL commands include SELECT (for retrieving data), UPDATE (for modifying rows), INSERT (for adding rows), CREATE (for defining tables), and DELETE (for removing rows).
How to Pass A SQL Interview?
Learn to write queries by hand, grasp JOINs and aggregations, understand window functions and CTEs, and effectively express your thinking while solving issues. Interviewers favor visible thought as much as perfect answers.
What Is SQL for Beginners?
It is a programming language that interacts with relational database management systems (RDBMS). This covers retrieving, updating, adding, and deleting data from tables.
Conclusion
Preparing for a SQL interview becomes a lot simpler when you stop seeing it as a list of definitions and instead regard it as a problem-solving exercise. Although the foundations remain important, real-world interviews frequently focus on JOINs, aggregations, subqueries, window functions, and query optimization.
These 40 SQL interview questions cover what interviewers will ask across all experience levels in 2026, from foundations to query writing and scenario issues.
The best-performing candidates didn’t rote-learn every term. They are the ones who can build a working query, show how it is built and talk through a performance problem.
Focus on the question sections. Practice the syntax until it is automatic. That’s what makes for offers.