Top 45+ SQL Query Interview Questions and Answers
| Summary: SQL interview preparation is more effective when you focus on approaching problems rather than memorizing queries. Practicing different types of questions, understanding why a query works, and explaining your reasoning can help you build confidence. This approach prepares you to handle unfamiliar questions and adapt your solutions when interviewers ask you to modify or explain your approach. |
SQL is a standardized language used to manage and work with data stored in relational databases. It is an important skill for roles such as SQL developers, database administrators, data analysts, and software developers. During interviews, candidates may be asked to explain SQL concepts, write queries, interpret results, or solve problems using sample data. Practicing SQL interview questions and answers can help you become familiar with these question types and prepare to apply your knowledge in practical interview scenarios. This blog covers questions ranging from basic SQL concepts to more advanced query-based problems.
Beginner-Level SQL Query Interview Questions for Freshers
SQL interviews often start with questions that test basic query and database concepts. Preparing for these questions can help entry-level candidates explain their approach clearly and build confidence before tackling more complex SQL problems. Here are some basic conceptual questions on SQL queries asked in interviews for freshers:
1. What is SQL?
SQL (Structured Query Language) is a standard language for interacting with relational databases. It lets you create, read, update, and delete data (CRUD operations), define and modify database structures like tables and schemas, and control access to data.
2. Describe a database.
A database is an organized collection of structured data stored electronically. In a relational database, this includes tables (which hold data in rows and columns), schemas (which define the structure), views (virtual tables built from queries), indexes (for faster lookups), and relationships between tables that maintain data integrity.
3. What are tables and fields in SQL?
A table is a database object that stores data in rows and columns. Each row represents a record, while each column represents a field or attribute that describes a particular type of information.


4. Explain the field in SQL in detail.
A field is a column in a database table that stores a specific type of information. Each field has a name and a defined data type, such as text, number, date, or Boolean.
For example:
| Table Name | Fields |
| Customers | Customer_name, customer_id, customer_phone, customer_address |
| Product | Product_name, product_id, product_price, product_quantity |
5. What is a QUERY in SQL?
An SQL query is a statement used to communicate with a database. It can retrieve, insert, update, or delete data, depending on the type of SQL statement being executed.
For example:
SELECT customer_name
FROM Customers;
This query retrieves the customer names from the Customers table.
6. What is a subquery in SQL?
A subquery is a query nested inside another SQL query. It can provide a value, a list of values, or a result set that the outer query uses for further processing.
For example –
SELECT column1, column2
FROM table1
WHERE column3 IN (
SELECT column3
FROM table2
WHERE condition
);
Here, the inner query runs as part of the outer query and provides the values used by the IN condition.
Read More: Preparing for SQL query-related interview questions? Explore the blog on the best websites to learn SQL.
7. What is the difference between the WHERE and HAVING clauses?
The main distinctions between these two clauses are –
| WHERE Clause | HAVING Clause |
| It cannot be used with aggregates. | It can be used with aggregates. |
| It acts as a pre-filter to sort and retrieve the data. | It behaves as a post-filter. |
| It filters the rows based on a condition or a column and is applied before any grouping takes place. | It filters groups using aggregate functions like sum, count, and average and is applied after grouping and filtering. |
8. Does SQL support other programming languages?
SQL can be used with programming languages such as Python, Java, and C# to interact with databases. These languages can connect to databases and execute SQL statements using database drivers, libraries, or APIs such as JDBC and ODBC.
Some database systems also provide procedural extensions to SQL. For example, Oracle Database uses PL/SQL, while Microsoft SQL Server uses T-SQL.
Therefore, SQL does not itself ‘support’ programming languages. Rather, programming languages can be used alongside SQL to build applications that interact with databases.
9. What is a trigger?
A trigger is a database object that automatically executes a predefined action when a specified event occurs in a database. Triggers can be associated with events such as INSERT, UPDATE, or DELETE. They can enforce business rules, maintain audit records, or automatically perform related database operations.
10. What is the main distinction between local and global variables?
The distinction between local and global variables depends on the specific SQL or procedural database system being used.
Generally, a local variable is declared within a specific procedure, function, or block and can be accessed only within its defined scope. A global variable has a broader scope and may be accessible across multiple procedures or sessions, depending on the database system.
Unlike general-purpose programming languages, SQL does not have one universal definition or implementation of local and global variables across all database systems.
11. What is a constraint?
A constraint is a rule applied to a table or column that controls the type of data stored and maintains data integrity. The common SQL constraints include:
- PRIMARY KEY: Uniquely identifies each row in a table.
- FOREIGN KEY: Establishes a relationship between tables.
- NOT NULL: Prevents a column from containing NULL values.
- UNIQUE: Ensures that values in a column or group of columns are unique.
- CHECK: Requires values to satisfy a specified condition.
- DEFAULT: Provides a default value when one is not explicitly supplied.
Pro Tip: Are you a fresher candidate and want to solve SQL query-based interview questions confidently? Explore the blog on the best SQL project ideas and strengthen your interview preparation skills.
Intermediate-Level SQL Query Interview Questions and Answers
Intermediate-level SQL interviews often require you to combine multiple concepts and write queries for practical data-related problems. The following SQL query-based interview questions and answers will help you practice applying SQL concepts, analyzing data, and explaining your approach during technical interviews.
12. Write a SQL query to return the first_name in uppercase from the EmpInfo table. Use the ALIAS name Emp_Name.
SELECT UPPER(first_name) AS Emp_Name FROM EmpInfo;
13. Create a query to determine how many people are employed in the “Finance” department.
SELECT COUNT(*) FROM EmpInfo WHERE Department = ‘Finance’;
14. To obtain the current date, create a query.
SELECT GETDATE ();
15. Create a query to get the EmployeeInfo table’s last_name column’s first four characters for each employee.
SELECT SUBSTRING (last_name, 1, 4) FROM EmpInfo;
16. In the Address column of the EmployeeInfo table, create a query to retrieve only the place name (the string before the brackets).
Using SUBSTRING
SELECT SUBSTRING (Address, 1, CHARINDEX (‘ (‘, Address)) FROM EmpInfo;
17. Construct a query to find the names of employees that begin with ‘P’.
SELECT * FROM EmpInfo WHERE first_name LIKE ‘P%’;
Pro Tip: As you work through these SQL queries asked in interview questions, you will understand them better once the basics of SQL are clear. You can learn the basics by taking a SQL course with AI and brushing up on the concepts.
18. Create a query to list all employees whose salaries are between 30000 and 60000.
SELECT * FROM EmpDetails WHERE Salary BETWEEN ‘30000’ AND ‘60000’;
19. Write a query to create a new table with information that has been copied from an existing table’s structure.
Using the SELECT INTO command:
SELECT * INTO NewTable FROM EmpInfo WHERE 1 = 0;
20. Write a query to retrieve the employee’s first_name and last_name in a single column as “Full_Name”. Both must be separated by space.
SELECT CONCAT (first_name, ‘ ‘,last_name) AS Full_Name From EmpInfo;
21. Create a query to derive all the records from the EmpInfo table such that the employee’s last_name is in descending order and the department is in ascending order.
SELECT * FROM EmpInfo
ORDER BY last_name desc,
Department asc;
22. Write a query to determine the total number of employees, grouped by gender, whose DOB is between 01/01/1975 and 31/12/1980.
SELECT COUNT(*), Gender
FROM EmpInfo
WHERE DOB BETWEEN ‘01/01/1975’ AND ‘31/12/1980’
GROUP BY Gender;
23. Create a query to retrieve information about employees whose last names contain five alphabets and the letter “A” as the final character.
The LIKE operator in SQL must be used to retrieve information about a specific value.
SELECT * FROM EmpInfo WHERE last_name LIKE ‘____a’;
SQL Query Interview Questions for Experienced Professionals
Experienced candidates can expect SQL interviews to go beyond basic syntax and definitions. Questions may involve writing complex queries, working with multiple tables, analyzing data, and choosing the right approach for a given problem. The interview queries for experienced professionals below cover the following areas:
24. What are the different types of constraints available in SQL?
They are as follows:
- NOT NULL: The column cannot store NULL values if it is designated as NOT NULL.
- Unique: Column or row values cannot be repeated.
- Primary Key: It is used to designate a table field as the primary key that is uniquely identified.
- Foreign Key: It is a field used to specifically identify each row in a different table.
- Check: It aids in ensuring that a column’s values satisfy a specific condition.
- Default: It specifies a default value for the column when no value is entered by the user.
25. How will you specify constraints? Write the syntax.
By using the CREATE TABLE statement or the ALTER TABLE statement for an existing table, we can specify constraints.
The syntax for using the CREATE TABLE statement for this SQL query asked in an interview is:
CREATE TABLE sample_table
(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
...
);
26. What are a primary key and a foreign key?
The primary key is an identifier that locates and retrieves each record in a table without scanning through the entire table. There cannot be more than one primary key in a table. A foreign key is a database constraint. It links two tables in a relational database.
27. What do you understand by left join and right join?
Left and right joins are outer joins used to combine data from two or more tables. The left join returns all the rows from the “left table” (from the left-hand side of the join keyword) and matches rows from the right-hand side of the join. The right join returns all the rows from the ‘right table’ (from the right-hand side of the JOIN keyword) and matches rows from the left-hand side of the join.
28. List the different types of relationships in SQL.
There are four main relationships in SQL:
- One-to-One (1:1) Relationship – Each record in the first table is associated with only one record in the second table, and vice-versa, by having a common attribute or key.
- One-to-Many (1:N) Relationship – Each record in the first table can be associated with multiple records in the second table. But each record in the second table is associated with only one record in the first table.
- Many-to-One (N:1) Relationship – It is the inverse of the one-to-many relationship. Each record in the second table is associated with multiple records in the first table. But each record in the first table is linked to only one record in the second table.
- Many-to-Many (N: N) Relationship – Each record in the first table can be associated with multiple records in the second table, and vice-versa. A junction table that contains foreign keys to both the first and second tables establishes this relationship.
29. What is the difference between the CHAR and VARCHAR2 data types in SQL?
CHAR and VARCHAR2 both store character data, but they handle length differently. CHAR is fixed length, meaning it always reserves the same amount of space regardless of how much data you actually store, padding the rest with spaces. VARCHAR2 is variable length, meaning it uses only as much space as the data requires, with no padding.
For example, if you store “Hi” in a CHAR(10) column, it still occupies 10 characters. The same value in a VARCHAR2(10) column occupies only 2 characters. In general, CHAR is useful when values are consistently the same length, like a two-letter state code, while VARCHAR2 suits values that vary in length, like names or addresses.
30. What are DDL Commands in SQL?
The structure of the database is defined and modified using Data Definition Language (DDL) commands. Some of the DDL commands are –
- CREATE: It is used to create a table, schema, etc.
- DROP: It removes a table and other database objects.
- DROP COLUMN: It removes a column from a table.
- ALTER: It is used to create, rename, remove, or alter the data type of columns.
- TRUNCATE: It removes all the data from a table without deleting the data structure.
31. Which Data Manipulation Language (DML) commands manipulate data in a database?
These DML queries are used to manipulate data in a database.
- SELECT: It is used to retrieve all or selected data from a table.
- INSERT: This command inserts values as records into the table.
- UPDATE: It updates the existing record in a table.
- DELETE: This removes a record from the table.
32. Explain the Data Control Language (DCL) commands.
The following commands manage database access rights and permissions:
- GRANT: It permits users to access database objects.
- REVOKE: It withdraws permissions from users to perform operations on database objects.
33. What are the Transaction Control Language (TCL) commands used in SQL queries?
Transaction control language (TCL) manages transactions within a database. It is employed to carry out the modifications made by the DML statements. The TCL commands in SQL are:
- BEGIN: It starts a new transaction.
- COMMIT: It saves transactions made on a database.
- ROLLBACK: It restores the previous transaction and thus, rollbacks the database.
- SAVEPOINT: As the name suggests, it sets a savepoint such that all the transactions made till the savepoint cannot be rollbacked, but after ones can be.
34. What is a stored procedure?
A stored procedure is a precompiled set of SQL statements stored in a database and executed as a single unit when you call it. It can accept parameters and perform operations such as retrieving, inserting, updating, or deleting data.
For example:
CREATE PROCEDURE GetEmployees
AS
SELECT * FROM Employees;
Here, GetEmployees is a stored procedure that retrieves all records from the Employees table.
35. State the benefits and drawbacks of stored procedures.
A stored procedure is a set of SQL statements stored in a database that can be executed when required.
a. Benefits:
- Improves performance by reducing repeated SQL parsing and compilation in some database systems.
- Allows code reuse across different applications or processes.
- Improves security by allowing users to execute procedures without giving them direct access to underlying tables.
- Reduces network traffic when a single procedure handles multiple database operations.
- Keeps related database operations together.
b. Drawbacks:
- Can be difficult to maintain when procedures become large or complex.
- May create database dependency because syntax varies across database systems.
- Can make debugging and testing more difficult compared with application-level code.
- Requires additional effort to manage database code with application code and version control.
Advanced-Level SQL Queries Interview Questions
The level of difficulty in writing SQL statements rises with complex queries. To become a successful SQL Developer, you must master the ability to handle complex queries. Here are a few complex SQL query interview questions –
36. Create a query to retrieve all information about employees excluding the employees with first names, “Tina” and “Maria” from the EmpInfo table.
SELECT *
FROM EmpInfo
WHERE first_name NOT IN ('Tina', 'Maria');
37. Construct a query to get details of employees with the address “MUMBAI(BOM)”.
SELECT *
FROM EmpInfo
WHERE Address LIKE "MUMBAI(BOM)% ";
38. Create a query to retrieve all employees who also hold EXECUTIVE positions.
SELECT E.first_name, E.last_name, P.Emp_postion
FROM EmpInfo E INNER JOIN EmployeePosition P ON
E.Emp_ID = P.Emp_ID AND P.Emp_position IN (‘EXECUTIVE’);
39. Make a query to derive the department-wise count of employees sorted by department’s count in ascending order.
SELECT Department, count(Emp_ID) AS EmpDeptCount
FROM EmpInfo GROUP BY Department
ORDER BY EmpDeptCount ASC;
40. Make a query to pull three minimum and maximum salaries from the EmpDetails table.
To retrieve three minimum salaries –
SELECT DISTINCT Salary
FROM EmpDetails E1
WHERE 3 >= (SELECT COUNT(DISTINCT Salary) FROM EmpDetails E2 WHERE E1.Salary >= E2.Salary)
ORDER BY E1.Salary DESC;
To retrieve three maximum salaries -
SELECT DISTINCT Salary
FROM EmpDetails E1
WHERE 3 >= (SELECT COUNT(DISTINCT Salary) FROM EmpDetails E2 WHERE E1.Salary >= E2.Salary)
ORDER BY E1.Salary DESC;
41. To fetch duplicate records from a table, create a query.
SELECT Emp_ID, first_name, Department, COUNT(*) AS NumOccurrences
FROM EmpInfo
GROUP BY Emp_ID, first_name, Department
HAVING COUNT(*) > 1;
42. Create a query to get a list of employees working in the same department.
SELECT DISTINCT E.Emp_ID, E.first_name, E.Department
FROM EmpInfo E
JOIN Employee E1 ON E.Department = E1.Department AND E.Emp_ID != E1.Emp_ID;
43. Find the five-highest salaries from the EmpDetails table.
SELECT TOP 1 salary
FROM
(SELECT TOP 5 Salary
FROM EmpDetails
ORDER BY salary DESC) AS emp
ORDER BY salary ASC;
44. Create a query to list the first and last records from the Emplnfo table.
To display the first record –
SELECT * FROM EmpInfo
WHERE Emp_ID = (SELECT MIN (Emp_ID)
FROM EmpInfo;
To display the last record -
SELECT * FROM EmpInfo
WHERE Emp_ID = (SELECT MAX (Emp_ID) FROM EmpInfo);
45. Create a SQL query to fetch 50% of the records from the EmpInfo table.
SELECT *
FROM EmpInfo WHERE
Emp_ID <= (SELECT COUNT (Emp_ID) / 2 FROM EmpInfo);
46. Make a SQL query to derive the last 5 records from the EmpInfo table.
SELECT * FROM EmpInfo WHERE
Emp_ID <= 5 UNION SELECT * FROM
(SELECT * FROM EmpInfo E ORDER BY E.Emp_ID DESC)
AS E1 WHERE E1.Emp_ID <=3;
Tips to Prepare for SQL Query Interview Questions
SQL interview preparation involves understanding how SQL works, applying concepts to different datasets, and explaining why you chose a particular approach. Use the following practical tips to prepare for SQL query interview questions and improve your speed, accuracy, and problem-solving skills.
- Practice SQL With Real-World Datasets: Work with employee, sales, customer, and transaction data to apply joins, filtering, grouping, subqueries, and aggregations to practical scenarios.
- Strengthen Advanced SQL Concepts: Revise CTEs, window functions, CASE statements, correlated subqueries, date functions, and ranking functions, as these can help you handle complex query-based problems.
- Focus on Query Performance: Learn how indexes, execution plans, joins, and filtering affect query efficiency. Practice rewriting queries to reduce unnecessary operations and improve performance.
- Solve Common Interview Problems: Prepare questions involving duplicate records, second-highest salaries, missing values, department-wise analysis, running totals, ranking, and consecutive dates.
- Practice Explaining Your Solution: After solving each query, explain your logic, the purpose of each clause, and why you selected a particular approach. It shows your understanding instead of relying on memorized solutions.


Conclusion
Practicing the SQL query interview questions and answers can help you assess how well you can apply database concepts to practical problems. Instead of focusing only on memorizing query syntax, use your preparation to build accuracy, logical thinking, and the ability to work with complex datasets. Regular practice can also help you identify common query patterns and improve your response time during interviews. Revising fundamentals alongside advanced SQL concepts will help you approach technical questions more structured and confidently.
Need more guidance to enhance your SQL journey? Check out our SQL Roadmap guide and enhance your skills.
